How do I get the name of a Java Enum type given its value?
I have written code which works for a particular Enum type, can I make it more generic?
The enum type:
public enum Category {
APPLE("3"),
ORANGE("1"),
GRAPE("GRAPE"),
BANANA("Banana");
private final String identifier;
/**
* Constructor.
*
* @param identifier
* - identfier.
*/
private Category(String identifier) {
this.identifier = identifier;
}
/**
* {@inheritDoc}
*/
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.equals(value)) {
return eachValue.name();
}
}
return enumValue;
}
}
解决方案
You should replace your getEnumNameForValue by a call to the name() method.