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")
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.
No comments:
Post a Comment