This tutorial is going to cover how to lookup Java enum from string value.

1. Lookup Enum From Value With Simple Enum Type

Let’s assume that we have a simple enum as follows:

To lookup a Java enum from its string value, we can use the built-in valueOf method of the Enum. However, if the provided value is null, the method will throw a NullPointerException exception. And if the provided value is not existed, an IllegalArgumentException exception. As a result, to be safe, we need to wrap the method call in a try…catch block.

To avoid such kind of try…catch block, we can create a method as follows:

As the enum is simple type, we can simply loop through all the values of Enum and compare those names with the given value.

2. Lookup Enum From Its Value With More Complex Enum Type

Let’s assume we have a little bit more complex Java enum as follows:

The enum now has a property “type” to represent its value. To lookup a Java enum from its string value like above, we will can have a method findByType as follows:

3. Conclusion

We have just gotten through how to lookup a Java enum from its string value by 2 examples. As mentioned above, this is useful in situations when we want to avoid multiple try..catch block and enable to look up an enum by different conditions such as lower case, upper case and abbreviation values of the enum.

And finally, a similar tutorial for C# can be found at C# Enum Method.

0 0 vote
Article Rating