Skip to content
Advertisement

Case-insensitive matching of a string to a Java enum

Java provides a valueOf() method for every Enum<T> object, so given an enum like

JavaScript

one can do a lookup like

JavaScript

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.

JavaScript

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.:

JavaScript

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.

Advertisement

Answer

I found getting the special blend of generics a little tricky, but this works.

JavaScript

Example

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement