Java program to lookup enum by string value
Here's a Java program to look up an enum by a string value:
enum Color { RED, GREEN, BLUE } public class Main { public static void main(String[] args) { String colorString = "GREEN"; Color color = Color.valueOf(colorString); System.out.println("Color enum value: " + color); } }Sourcewww:.theitroad.com
In this program, we first define an enum
called Color
with three values: RED
, GREEN
, and BLUE
.
We then initialize a String
variable colorString
with the value "GREEN"
, which is the name of one of the Color
enum values.
To look up the Color
enum value corresponding to colorString
, we use the static valueOf
method of the Color
enum, passing in the String
value as an argument. This method returns the corresponding Color
enum value.
Finally, we print out the value of the Color
enum variable.
The output of this program will be:
Color enum value: GREEN
Note that the valueOf
method throws an IllegalArgumentException
if the specified string is not a valid name of an enum constant. To avoid this exception, you can use the EnumUtils.getEnum
method from the Apache Commons Lang library, which returns null
if the specified enum constant does not exist.