java - 在扩展 Enum 的泛型类中使用 Enum.values

标签 java generics enums

<分区>

我正在尝试使用枚举中的所有可用值初始化一个通用类。这是我希望它的工作方式:

public class MyClass<E extends Enum<E>> {

    E[] choices;

    public MyClass() {
        choices = E.values();
    }

但是,在 Eclipse 中不接受对 E.values 的调用,表示此 E 未定义此方法。

可以接受使用此构造函数,但需要调用者提供值:

public MyClass(E[] e) {
    choices = e;
}

在我找到的文档中:

Java programming language enum types are much more powerful than their counterparts in other languages. The enum declaration defines a class (called an enum type). The enum class body can include methods and other fields. The compiler automatically adds some special methods when it creates an enum. For example, they have a static values method that returns an array containing all of the values of the enum in the order they are declared.

有没有办法解决这个问题?

最佳答案

您最好的选择可能是将所需枚举的 Class 传递给构造函数。 (例如,查看 EnumMap 是如何构建的。)

然后您可以使用clazz。 getEnumConstants () 获取常量。

关于java - 在扩展 Enum 的泛型类中使用 Enum.values,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11663914/

相关文章:

java - 打印 doOnError 的响应

java - 添加触摸事件监听器到android Canvas

Java 类泛型

当枚举位于类内部时,Java 枚举反射

c# - 在 C# 中使用 Value 属性从 Xml 中反序列化枚举

java - 我将如何进行输入验证?

Java 按年龄划分颜色

c# - 具有子泛型类型的泛型工厂方法

java - 如何将数组中的通用对象设置为 0/null?

python - 如何在 cython 中访问枚举?