如何处理 Java 中的泛型枚举?
所以,我有一个抽象类,例如:
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
}
}
感谢 LOADS to mdma,你应该得到比我能给的更多的积分。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
EDIT2:超类和接口上的泛型不会被删除。您可以在运行时获取泛型类型并使用它来获取枚举值。请参阅 Class.getGenericSuperclass。这将使您不必在构造函数中传递值或类。
原来的:
你不能用泛型来做到这一点。但是,如果您还传递相应的类,例如像
“Then”这样的构造函数,您可以使用它通过编辑获取相应的枚举值
:尽管客户不是专业程序员,但编译器将确保传递正确的类。您还可以通过提供示例和单元测试来清楚地说明用法。
您还可以让构造函数获取 Enum 的实际值,并从中派生类。这可能更容易使用,因为参数是
E
而不是更“可怕”的Class
。例如
EDIT2: Generics on superclasses and interfaces are not erased. You can get the generic type at runtime and use that to fetch the enum values. See Class.getGenericSuperclass. This will save you having to pass the value or a class in the constructor.
Original:
You cannot do this with generics. However, if you pass in the corresponding class also, e.g. a constructor like
Then you can use that to fetch the corresponding enum values via
EDIT: Although the clients are not professional programmers, the compiler will ensure the correct class is passed. You can also make the usage clear by providing examples, and unit tests.
You could also have the constructor take and actual value of the Enum, and derive the class from that. This might be simpler to use, since the parameter is then an
E
rather than the more "scary"Class<E>
.E.g.
由于泛型在运行时被删除,因此唯一可能的方法是使用一个需要
Class
参数的构造函数,然后您可以在该参数上调用getEnumConstants()
。Since generics are erased at runtime, the only way this is possible is by having a constructor that requires a
Class<E>
parameter on which you can then callgetEnumConstants()
.