Tuesday, 13 December 2016

Java Enum get value from String

Problem:

In Java, I have an Enum and I'd like to be able to look up one of its value using a String.

Solution:

In order to get a specific Enum value from a String, use the java.lang.Enum.valueOf() function.

For instance, if I have the following Enum:

enum Day {Mo, Tu, We, Th, Fr, Sa, Su}

Then the following code gets Day.Th from the String "Th":

Day.valueOf("Th")
Another example, assuming the above Enum Day is defined:
Day myDayExample;
myDayExample = Day.valueOf("Th");

System.out.println(myDayExample); // prints: Th

Notes:

If either the Enum type or string is null, then java.lang.Enum.valueOf() will throw a NullPointerException.

Additionally, if no Enum constant with the name in the String exists, an IllegalArgumentException will be thrown.

For more information, check out the references below.

References:

No comments:

Post a Comment