Java getting the Enum name given the Enum Value

Julia picture Julia · Oct 8, 2010 · Viewed 141.2k times · Source

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;
    }
}

Answer

Riduidel picture Riduidel · Oct 8, 2010

You should replace your getEnumNameForValue by a call to the name() method.