【发布时间】:2012-12-19 18:29:14
【问题描述】:
我有两个枚举类,比如 Enum1 和 Enum2:
enum Enum1 {ONE, TWO, THREE}
enum Enum2 {FOUR, FIVE}
我有这样的方法:
public <E extends Enum<E>> method (E arg) {
switch (arg) { // Here is the compile error -- Cannot switch
// on a value of type E. Only convertible int
// values, strings or enum variables are permitted
// (And of course, all the cases are incorrect
// because the enum set is unknown)
case ONE:
// do something
case TWO:
// do something
case THREE:
// do something
case FOUR:
// do something
case FIVE:
// do something
default:
// do something
}
}
那么可以切换泛型枚举类型的值吗?
有一种方法可以将其更改为字符串(仅适用于 JDK7):
public <E extends Enum<E>> method (E arg) {
switch (arg.name()) {
case "ONE":
// do something
case "TWO":
// do something
case "THREE":
// do something
case "FOUR":
// do something
case "FIVE":
// do something
default:
// do something
}
}
【问题讨论】:
-
你看过任何 Enum 文档吗?
-
即使有可能,这两个枚举也不会相互关联。您不能针对 case FOUR 或 FIVE 值测试 Enum1。所以你的代码以这种方式编写没有意义。
-
@Heisenbug,嗯,我知道。我不会在真正的项目中这样做,我只是在尝试这种语言。因为所有的枚举类型都是从 java.lang.Enum 隐式派生的,所以我认为不同的枚举类型之间应该有一些通用的关系,我试过了。所以在 JDK7 中,有一种方法可以做到这一点——打开 arg.name() 并在 case 语句中引用所有内容(name() 得到一个字符串,该字符串准确地表示它在其枚举声明中声明的内容)——当然是一些琐碎的发现,但只是为了好玩!
-
@shuangwhywhy:我的评论无意批评,抱歉。我只是指出这一点。总是很高兴看到人们尝试使用这种语言;)
标签: java enums switch-statement