How to retrieve values from a Java enumeration class?
To obtain the values of a Java enum class, you can use the following method:
- list of values
- return the values contained in the object
For example, suppose there is an enumeration class called Color, you can retrieve all enumeration values in the following way:
Color[] colors = Color.values();
for (Color color : colors) {
// 处理每个枚举值
}
- return the value represented by this object
- determine the value of()
For example, if the Color enum class has an enum value called RED, you can retrieve this enum value as follows:
Color red = Color.valueOf("RED");
It is important to note that the valueOf() method is case-sensitive, and if the provided name does not exactly match any of the enum values’ names, it will throw an IllegalArgumentException.
Furthermore, you can also use the name() method to retrieve the name of the enum value, for example:
Color color = Color.RED;
String name = color.name(); // 返回字符串"RED"
I hope the above information can help you!