因此,我有一个抽象类,如下所示:
public abstract class AbstractParent <E extends Enum<E>> {...}在AbstractParent中的某个非抽象方法中,我想遍历E的值。这可能吗?
更好的例子是:
public abstract class AbstractParent <E extends Enum<E>> {
...
protected void doSomething() {
//iterate over the values of E and perform an action using them
}
}
public class Child extends AbstractParent<Child.Index> {
public static enum Index {
...
}
public Child() {
super();
this.doSomething(); //this should iterate over Index's values
}
}编辑:
因此,多亏了mdma,它才能很好地工作:
public abstract class AbstractParent <E extends Enum<E>> {
...
protected void doSomething() {
//iterate over the values of E and perform an action using them
ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass();
Type t = pt.getActualTypeArguments()[0];
E[] enumValues = ((Class<E>)t).getEnumConstants();
// enumValues is now an iterable array of the values inside Index
}
}
public class Child extends AbstractParent<Child.Index> {
public static enum Index {
...
}
public Child() {
super();
this.doSomething(); //this should iterate over Index's values
}
}感谢mdma,你应该得到比我更多的分数。
发布于 2010-07-03 04:32:39
EDIT2:超类和接口上的泛型不会被擦除。您可以在运行时获取泛型类型,并使用它来获取枚举值。参见Class.getGenericSuperclass。这将使您不必在构造函数中传递值或类。
原始:你不能用泛型做到这一点。但是,如果您还传入了相应的类,例如像这样的构造函数
AbstractParent(Class<E> enumClass)
{
this.enumClass = enumClass;
}然后,您可以使用它来获取相应的枚举值
public E[] getValues()
{
return this.enumClass.getEnumConstants();
}编辑:虽然客户端不是专业的程序员,但编译器将确保传递正确的类。您还可以通过提供示例和单元测试来清楚地说明用法。
您还可以让构造函数接受Enum的实例值,并从中派生类。这可能更容易使用,因为参数是一个E,而不是更“可怕”的Class<E>。
例如。
AbstractParent(E enumValue)
{
this.enumClass = enumValue.getClass();
}发布于 2010-07-03 04:24:29
由于泛型在运行时被擦除,因此唯一可能做到这一点的方法是使用一个构造函数,该构造函数需要一个Class<E>参数,然后可以对该参数调用getEnumConstants()。
https://stackoverflow.com/questions/3168888
复制相似问题