Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java getting the Enum name given the Enum Value

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;     } } 
like image 535
Julia Avatar asked Oct 08 '10 09:10

Julia


People also ask

Can we get an enum by value?

Get the value of an EnumTo get the value of enum we can simply typecast it to its type. In the first example, the default type is int so we have to typecast it to int. Also, we can get the string value of that enum by using the ToString() method as below.

What does enum name return in Java?

The name() method of Enum class returns the name of this enum constant same as declared in its enum declaration.

What does enum valueOf return?

valueOf. Returns the enum constant of the specified enum type with the specified name. The name must match exactly an identifier used to declare an enum constant in this type. (Extraneous whitespace characters are not permitted.)


2 Answers

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

like image 92
Riduidel Avatar answered Sep 18 '22 10:09

Riduidel


Try below code

public enum SalaryHeadMasterEnum {      BASIC_PAY("basic pay"),     MEDICAL_ALLOWANCE("Medical Allowance");      private String name;      private SalaryHeadMasterEnum(String stringVal) {         name=stringVal;     }     public String toString(){         return name;     }      public static String getEnumByString(String code){         for(SalaryHeadMasterEnum e : SalaryHeadMasterEnum.values()){             if(e.name.equals(code)) return e.name();         }         return null;     } } 

Now you can use below code to retrieve the Enum by Value

SalaryHeadMasterEnum.getEnumByString("Basic Pay") 

Use Below code to get ENUM as String

SalaryHeadMasterEnum.BASIC_PAY.name() 

Use below code to get string Value for enum

SalaryHeadMasterEnum.BASIC_PAY.toString() 
like image 33
prashant thakre Avatar answered Sep 18 '22 10:09

prashant thakre