How to get an enum value from a string value in Java
To get an enum value from a string value in Java, you can use the valueOf
method of the enum
type. Here's an example of how you might do this:
public enum Color {
RED, GREEN, BLUE
}
// ...
String colorString = "RED";
Color color = Color.valueOf(colorString);
This will convert the string value to the corresponding enum value.
Keep in mind that the valueOf
method will throw an IllegalArgumentException
if the specified string does not match any of the enum values. You can catch this exception or use the Enum.valueOf
method, which takes an additional parameter specifying the type of the enum and returns null
if the value is not found.
For example:
Color color = Enum.valueOf(Color.class, colorString);
I hope this helps! Let me know if you have any other questions.