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:
1 2 3 4 5 6 7 |
public enum ComponentType { CATALOG, PRODUCT, ORDER, PAYMENT, USER; } |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
public enum ComponentType { CATALOG, PRODUCT, ORDER, PAYMENT, USER; public static ComponentType findByValue(String componentType) { for (ComponentType compType : values()) { if (compType.name().equals(componentType)) { return compType; } } return null; } } |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
public enum ComponentType { CATALOG("C"), PRODUCT("PD"), ORDER("O"), PAYMENT("PM"), USER("U"); String type; ComponentType(String type) { this.type = type; } } |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
public enum ComponentType { CATALOG("C"), PRODUCT("PD"), ORDER("O"), PAYMENT("PM"), USER("U"); String type; ComponentType(String type) { this.type = type; } public static ComponentType findByType(String componentType) { for (ComponentType compType : values()) { if (compType.type.equals(componentType)) { return compType; } } return null; } } |
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.