我有一个枚举,其中在 Constants 类中包含一些名称:
static final enum NAMES {
One,
Two,
Three,
Four,
Five
}
我尝试通过以下方式浏览它们:
for (Constants.NAMES name in Constants.NAMES.values())
然后在 switch 中使用它们:
switch (index.key) {
case Constants.NAMES.One:
我还尝试仅使用 One 作为案例,使用 Enumset 作为循环,唯一有效的方法是使用“One”作为字符串,但这违背了 Enum 的目的
这正在工作:
for (Constants.NAMES script : Constants.NAMES.values()) {
switch (index.key) {
case Constants.NAMES.ONE.name():
最佳答案
定义您的枚举如下:
enum NAMES {
ONE, TWO, THREE, FOUR, FIVE
}
static final
与声明枚举一起使用时是非法修饰符。还要确保仅使用大写字母定义常量。
然后使用它:
public static void main(String[] args) {
String myStr = "something";
switch (NAMES.valueOf(myStr)) {
case ONE:
break;
case TWO:
break;
// the rest
default:
break;
}
}
<小时/>
或者,您可以创建一个静态方法来从枚举
中获取结果
enum NAMES {
ONE, TWO, THREE, FOUR, FIVE;
public static NAMES fetchValue(String constant) {
NAMES name = null;
for (NAMES num : EnumSet.allOf(NAMES.class)) {
if (num.name().equals(constant)) {
name = NAMES.valueOf(constant);
}
}
return name;
}
}
并使用以下方式调用它:
NAMES names = NAMES.fetchValue("ONE");
在这种方法中,即使没有找到常量,代码也不会中断。
关于java - 枚举值不与 switch 中的枚举进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53593979/