ags*_*ags 3 java generics enums class
动机:我想构建一个枚举,代表某些价值家族的所有可能价值(我在这里犹豫说"阶级").枚举将有其他方法,字段,甚至可能实现其他接口.然后我想将这个枚举传递给另一个方法,它将迭代所有可能的值(使用Enum.values()并做一些工作.
我研究过,发现枚举Foo真的变成了Foo extends Enum<Foo>.这就是为什么我不能扩展枚举.我试图将我的方法参数定义为:
myMethod(Class<?> bar) {...}
myMethod(Class<? extends Enum> bar) {...}
myMethod(Class<? extends Enum<?>> bar) {...}
Run Code Online (Sandbox Code Playgroud)
但在我尝试基本的方法时,在方法内部:
int i = bar.values().length;
Run Code Online (Sandbox Code Playgroud)
它失败.有没有其他方法可以做到这一点(或避免这样做)?
注意:我可以传递枚举的实际实例并用于bar.getDeclaringClass()查找枚举类(而不是实例),但这非常难看.
Pau*_*ora 11
尝试使用以下内容:
<E extends Enum<E>> void myMethod(Class<E> enumType) {
E[] values = enumType.getEnumConstants();
...
}
Run Code Online (Sandbox Code Playgroud)
返回此枚举类的元素,如果此Class对象不表示枚举类型,则返回null.
编辑:如果您使用实现共享接口的不同枚举类型,则可以修改方法以便能够调用接口方法.例如:
interface Fooable {
void foo();
}
...
<E extends Enum<E> & Fooable> void myMethod(Class<E> enumType) {
E[] values = enumType.getEnumConstants();
for (E value : values) {
value.foo();
}
}
Run Code Online (Sandbox Code Playgroud)