How to get an enum value from a string value in Java
Yes, Blah.valueOf("A")
will give you Blah.A
.
Note that the name must be an exact match, including case: Blah.valueOf("a")
and Blah.valueOf("A ")
both throw an IllegalArgumentException
.
The static methods valueOf()
and values()
are created at compile time and do not appear in source code. They do appear in Javadoc, though; for example, Dialog.ModalityType
shows both methods.
How to get Enum value from String value of one of it's attributes
Solution:
@AllArgsConstructor
@Getter
public enum ExternalEnum {
enum1("red", "1"),
enum2("black", "2"),
enum3("blue", "3");
private String colour;
private String number;
// you can call this method with number or name but you have to change
//parameter accordingly
public static ExternalEnum findByNumber(String number) {
for(ExternalEnum type : values()) {
if(type.equals(number)) {
return type;
}
}
}
}
Getting String value from enum in Java
if status
is of type Status
enum, status.name()
will give you its defined name.
Getting java enum by name
Each Java enum has method valueOf(String name)
which returns enum by name.
MyEnum foo = MyEnum.valueOf("TOTO");
MyEnum bar = MyEnum.valueOf("ZOZO");
Convert String to equivalent Enum value
Hope you realise, java.util.Enumeration
is different from the Java 1.5 Enum types.
You can simply use YourEnum.valueOf("String")
to get the equivalent enum type.
Thus if your enum is defined as so:
public enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY
}
You could do this:
String day = "SUNDAY";
Day dayEnum = Day.valueOf(day);
How to cast a String value to an Enum value by Class?
It's actually kind of a pain because of the way Enum
is declared. You wouldn't be able to call valueOf
with a Class<?>
(nor e.g. a Class<? extends Enum<?>>
). The only way to do it without unchecked casting is to go through getEnumConstants
:
public boolean tryCast(String value){
for(Object o : enumClass.getEnumConstants()) {
Enum<?> e = (Enum<?>) o;
if(e.name().equals(value))
return true;
}
return false;
}
If you don't care about the unchecked cast you can do:
try {
Enum.valueOf( (Class) enumClass, value );
return true;
} catch(IllegalArgumentException e) {
return false;
}
But, you know, some people will grumble because it's a raw type. getEnumConstants
is probably better anyways since then you don't use exceptions for this kind of thing.
In addition, since you have a Class<?>
you might want to perform a check like
if( !Enum.class.isAssignableFrom(enumClass) )
return false;
or throw an exception in the constructor.
Java: How to get an enum value to a string?
You can inject the enum's value, as a String:
public void checkIfRecordIsUsed(String record, testEnum test) {
List<String> data = new ArrayList<String>();
Query dataQuery = entityManager.createNativeQuery("select * from DATA where test_a = ?2 and prg_l = ?1");
dataQuery.setParameter(1, record);
dataQuery.setParameter(2, test.name());
if (dataQuery.getResultStream().findAny().isPresent())
tablesWithRecords.add("DATA");
}
Getting Enum value by another value
The ENUM types has the method values
, which you can use to extract all the enum values and compare their identifier against the one that you have passed by the method parameter, namely:
public MyEnum getEnum(String identifier){
for(MyEnum e : MyEnum.values())
if(e.identifier.equals(identifier))
return e;
return null;
}
or even better:
public static Optional<MyEnum> getEnum(String identifier){
return Arrays.stream(MyEnum.values()).filter(i -> i.identifier.equals(identifier)).findFirst();
}
This way you make it clear on the method signature that you might or not find the enum.
Related Topics
Java Command Not Found on Linux
Java_Home and Path Are Set But Java -Version Still Shows the Old One
What Is the Point of the Diamond Operator (≪≫) in Java
How to Resolve Classnotfoundexception
Scanner Is Skipping Nextline() After Using Next() or Nextfoo()
How to Write a Correct Micro-Benchmark in Java
How to Add Jtable in Jpanel With Null Layout
What's the Simplest Way to Print a Java Array
What Is a Stack Trace, and How to Use It to Debug My Application Errors
How to Upload Files to a Server Using Jsp/Servlet
How to Generate Random Integers Within a Specific Range in Java
What Is a Serialversionuid and Why Should I Use It
How to Append Text to an Existing File in Java