How can I get the name of a Java Enum type given its value?
I have the following code which works for a particular Enum type, can I make it more generic?
public enum Category {
APPLE("3"),
ORANGE("1"),
private final String identifier;
private Category(String identifier) {
this.identifier = identifier;
}
public String toString() {
return identifier;
}
public static String getEnumNameForValue(Object value){
Category[] values = Category.values();
String enumValue = null;
for(Category eachValue : values) {
enumValue = eachValue.toString();
if (enumValue.equalsIgnoreCase(value)) {
return eachValue.name();
}
}
return enumValue;
}
}
Try below code
Now you can use below code to retrieve the Enum by Value
Use Below code to get ENUM as String
Use below code to get string Value for enum
Here is the below code, it will return the Enum name from Enum value.
Try, the following code..
You should replace your
getEnumNameForValue
by a call to thename()
method.