gpt4 book ai didi

java - 从单个字符解码 Java 枚举

转载 作者:行者123 更新时间:2023-12-01 16:44:12 25 4
gpt4 key购买 nike

我有

No enum constant [...] at java.lang.Enum.valueOf(Enum.java:238)

当我尝试将单个字符字符串解码为枚举时。

出了什么问题,如何修复?

public class testEnum {

public enum Colors {
RED("R"), GREEN("G"), BLUE("B");
private final String code;

Colors(String code) {
this.code = code;
}

public String getCode() {
return code;
}

}

public static void main(String args[]) throws Exception {
Colors c = Colors.valueOf("R");
System.out.println(c);
}
}

在本例中,我希望输出控制台显示 RED

最佳答案

Colors.valueOf("R") 是一个隐式声明的方法,也是 Enum.valueOf(Colors.class, "R") 的快捷方式。

The documentation of Enum.valueOf

@param name the name of the constant to return

您的常量是REDGREENBLUE

You may wanna get an enum instance by its field.

关于java - 从单个字符解码 Java 枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56019394/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com