动机:我想构建一个枚举,代表某些价值家族的所有可能价值(我在这里犹豫说“阶级”).枚举将有其他方法,字段,甚至可能实现其他接口.然后我想将这个枚举传递给另一个方法,它将迭代所有可能的值(使用Enum.values()并做一些工作.
我研究过并发现enum Foo实际上变成了Foo扩展Enum< Foo>.这就是为什么我不能扩展枚举.我试图将我的方法参数定义为:
myMethod(Class> bar) {...}
myMethod(Class extends Enum> bar) {...}
myMethod(Class extends Enum>> bar) {...}
但是当我尝试基本的东西时,在方法内部:
int i = bar.values().length;
它失败.还有其他方法可以做到这一点(或者避免需要这样做)吗?
注意:我可以传递枚举的实际实例并使用bar.getDeclaringClass()来查找枚举类(而不是实例),但这非常难看.
解决方法:
尝试使用以下内容:
> void myMethod(Class enumType) {
E[] values = enumType.getEnumConstants();
...
}
Returns the elements of this enum class or null if this Class object
does not represent an enum type.
编辑:如果您使用实现共享接口的不同枚举类型,则可以修改方法以便能够调用接口方法.例如:
interface Fooable {
void foo();
}
...
& Fooable> void myMethod(Class enumType) {
E[] values = enumType.getEnumConstants();
for (E value : values) {
value.foo();
}
}
标签:java,enums,class,generics
来源: https://codeday.me/bug/20190716/1480055.html