EN
Java - convert String to Enum object
6 points
Short solution:
xxxxxxxxxx
1
public class Example1 {
2
3
enum ColorEnum {
4
RED,
5
GREEN,
6
BLUE
7
}
8
9
public static void main(String[] args) {
10
11
String color = "BLUE";
12
13
// we use valueOf on our enum class
14
ColorEnum colorEnum = ColorEnum.valueOf(color);
15
16
System.out.println(colorEnum); // BLUE
17
}
18
}
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 ...
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) |
xxxxxxxxxx
1
public class Example2 {
2
3
enum ColorEnum {
4
RED,
5
GREEN,
6
BLUE
7
}
8
9
public static void main(String[] args) {
10
11
String color = "blue";
12
color = color.toUpperCase();
13
14
ColorEnum colorEnum = ColorEnum.valueOf(color);
15
System.out.println(colorEnum); // BLUE
16
}
17
}
Output:
xxxxxxxxxx
1
BLUE
xxxxxxxxxx
1
public class Example3 {
2
3
enum ColorEnum {
4
RED,
5
GREEN,
6
BLUE
7
}
8
9
public static void main(String[] args) {
10
11
String color = "WHITE";
12
ColorEnum colorEnum = ColorEnum.valueOf(color);
13
14
System.out.println(colorEnum);
15
}
16
}
Output:
xxxxxxxxxx
1
Exception in thread "main" java.lang.IllegalArgumentException:
2
No enum constant com.dirask.Example3.ColorEnum.WHITE
3
at java.lang.Enum.valueOf(Enum.java:238)