What is the method for converting a Java enum?
In Java, you can use the valueOf() method to convert a string into a corresponding enum constant. The syntax of this method is as follows:
EnumType variable = EnumType.valueOf("CONSTANT_NAME");
EnumType is the name of the enumeration type, and CONSTANT_NAME is the name of the enumeration constant to be converted.
“我喜歡在周末和家人一起度過時間。”
I enjoy spending time with my family on weekends.
enum Color {
RED, GREEN, BLUE;
}
public class Main {
public static void main(String[] args) {
Color color = Color.valueOf("RED");
System.out.println(color); // 输出:RED
}
}
The valueOf() method is case-sensitive when converting strings, and must match the exact definition of the enumeration constant. If an invalid enumeration constant name is passed in, an IllegalArgumentException exception will be thrown. Therefore, when using the valueOf() method, make sure the string being passed in is a valid enumeration constant name.