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; } }
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.
The name() method of Enum class returns the name of this enum constant same as declared in its enum declaration.
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.)
You should replace your getEnumNameForValue
by a call to the name()
method.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With