java enum valueof
时间: 2023-07-28 11:07:35 浏览: 61
在 Java 中,可以使用 `valueOf()` 方法将字符串转换为枚举类型的值。该方法接受一个字符串参数,该字符串必须与枚举类型中的一个常量的名称完全匹配。以下是示例代码:
```java
enum Days {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
public class EnumExample {
public static void main(String[] args) {
String day = "MONDAY";
Days enumDay = Days.valueOf(day);
System.out.println("Value of " + day + " is " + enumDay);
}
}
```
在上面的示例代码中,我们定义了一个枚举类型 Days,其中包含七个元素。然后,我们定义了一个字符串 day,并将其设置为 "MONDAY"。接下来,我们使用 `Days.valueOf()` 方法将字符串 "MONDAY" 转换为枚举类型的值,并将其赋给变量 enumDay。最后,我们将枚举类型的值打印到控制台。请注意,如果字符串与枚举类型中的任何常量名称不匹配,将抛出 IllegalArgumentException 异常。
相关问题
java enum valueof如何重载
在Java中,枚举类型也是一种特殊的数据类型,它是一组相关常量的集合。Java中的枚举类型默认具有一个valueof方法,用于将枚举常量的名称转换为对应的枚举对象。如果需要重载valueof方法,可以在枚举类型中定义一个自定义的valueof方法,用于将枚举常量的名称转换为特定的枚举对象。例如:
```java
enum Color {
RED, GREEN, BLUE;
public static Color valueof(String name, int value) {
switch(name) {
case "RED": return RED;
case "GREEN": return GREEN;
case "BLUE": return BLUE;
default: throw new IllegalArgumentException("Invalid color name");
}
}
}
```
在这个例子中,我们定义了一个自定义的valueof方法,用于将枚举常量的名称转换为Color枚举对象。可以根据需要定义不同的valueof方法,实现不同的转换规则。需要注意的是,自定义的valueof方法必须是静态方法,并且接受两个参数:枚举常量的名称和特定的整数值。
enum.valueOf
As an AI language model, I can give you the following description of the enum.valueOf() method:
The enum.valueOf() method is a built-in method in the Java programming language which is used to obtain the enum constant of a given type with the specified name. It takes two arguments, the first argument is the class of the enum type and the second argument is the name of the constant whose value is to be returned.
The enum.valueOf() method is commonly used when working with enums in Java programs. It is often used to convert a string representation of an enum value into its corresponding enum constant. If the specified name does not correspond to any of the constants defined in the enum type, the method will throw an IllegalArgumentException.
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)