views:

50

answers:

1

Hi,

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

Thanks, Julia.

+1  A: 

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

Riduidel
@Jukia: Also, consider overriding `toString()`: http://download.oracle.com/javase/6/docs/api/java/lang/Enum.html#toString%28%29
trashgod
@trashgod: She is overriding toString
Thilo
@Thilo: My error; thanks. @Julia: Sorry about misspelling your name.
trashgod