To get an enum value from a string in Java, you can use the valueOf() method provided by the enum class. This method converts a string to the corresponding enum constant. Here’s an example:
public enum Color {
RED, GREEN, BLUE;
}
String colorName = “GREEN”;
Color color = Color.valueOf(colorName); // Returns Color.GREEN
If the string does not match any enum constant, valueOf() will throw an IllegalArgumentException. To avoid this, you can use a try-catch block or the EnumUtils.getEnum() method from Apache Commons Lang for safer handling.