EN
Java - convert String to Enum object
6
points
Short solution:
public class Example1 {
enum ColorEnum {
RED,
GREEN,
BLUE
}
public static void main(String[] args) {
String color = "BLUE";
// we use valueOf on our enum class
ColorEnum colorEnum = ColorEnum.valueOf(color);
System.out.println(colorEnum); // BLUE
}
}
In java we can simply convert String to enum by using .valueOf()
method on our Enum class.
Example:
MyEnumClass.valueOf("MY_ENUM_CONSTANT")
Note:
We need to use the name of enum value exactly like it is defined.
- letter size must be the same
- if uppercase letters then we need to use uppercase
- if lowercase letters then we need to use lowercase
- no spaces
- no white spaces
If we don't have exact match then we get exception:
java.lang.IllegalArgumentException: No enum constant ...
1. Documentation - Enum valueOf() method
Syntax | valueOf(String name) Called on Enum class eg ColorEnum.valueOf("BLUE") |
Parameters | name - String, the name of the constant to return |
Result | the enum constant of the specified enum type with the specified name Example type: ColorEnum |
Description |
|
Throws | IllegalArgumentException – if this enum type has no constant with the specified name (exatch match required - letter size must match, no spaces, no whitespaces) |
2. Using Enum value() and String.toUpperCase()
public class Example2 {
enum ColorEnum {
RED,
GREEN,
BLUE
}
public static void main(String[] args) {
String color = "blue";
color = color.toUpperCase();
ColorEnum colorEnum = ColorEnum.valueOf(color);
System.out.println(colorEnum); // BLUE
}
}
Output:
BLUE
3. Case with No enum constant
public class Example3 {
enum ColorEnum {
RED,
GREEN,
BLUE
}
public static void main(String[] args) {
String color = "WHITE";
ColorEnum colorEnum = ColorEnum.valueOf(color);
System.out.println(colorEnum);
}
}
Output:
Exception in thread "main" java.lang.IllegalArgumentException:
No enum constant com.dirask.Example3.ColorEnum.WHITE
at java.lang.Enum.valueOf(Enum.java:238)