Java
provides a valueOf()
method for every Enum<T>
object, so given an enum
like
public enum Day { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday }
one can do a lookup like
Day day = Day.valueOf("Monday");
If the string passed to valueOf()
does not match (case sensitive) an existing Day
value, an IllegalArgumentException
is thrown.
To do a case-insensitive matching, one can write a custom method inside the Day
enum, e.g.
public static Day lookup(String day) { for (Day d : Day.values()) { if (d.name().equalsIgnoreCase(day)) { return type; } } return null; }
Is there any generic way, without using caching of values or any other extra objects, to write a static lookup()
method like the above only once (i.e., not for every enum
), given that the values()
method is implicitly added to the Enum<E>
class at compile time?
The signature of such a "generic" lookup()
method would be similar to the Enum.valueOf()
method, i.e.:
public static <T extends Enum<T>> T lookup(Class<T> enumType, String name);
and it would implement exactly the functionality of the Day.lookup()
method for any enum
, without the need to re-write the same method for each enum
.
Enum 's valueOf(String) Method Careful, the strings passed to valueOf are case sensitive!
Because there is only one instance of each enum constant, it is permissible to use the == operator in place of the equals method when comparing two object references if it is known that at least one of them refers to an enum constant.
equals method uses == operator internally to check if two enum are equal. This means, You can compare Enum using both == and equals method.
You can create Enum from String by using Enum. valueOf() method. valueOf() is a static method that is added on every Enum class during compile-time and it's implicitly available to all Enum along with values(), name(), and cardinal() methods.
I found getting the special blend of generics a little tricky, but this works.
public static <T extends Enum<?>> T searchEnum(Class<T> enumeration, String search) { for (T each : enumeration.getEnumConstants()) { if (each.name().compareToIgnoreCase(search) == 0) { return each; } } return null; }
Example
public enum Horse { THREE_LEG_JOE, GLUE_FACTORY }; public static void main(String[] args) { System.out.println(searchEnum(Horse.class, "Three_Leg_Joe")); System.out.println(searchEnum(Day.class, "ThUrSdAy")); }
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