15

I am trying to initialise a generic class with all the availables values from an Enum. HEre is how I would like it to work:

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

    E[] choices;

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

However, the call to E.values is not accepted in Eclipse saying that this method is undefined for this E.

Using this constructor instead is accepted, but requires the caller to provide the values:

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

In the documentation I found:

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.

Is there a way to workaround this issue ?

Olivier.Roger
  • 4,241
  • 5
  • 40
  • 68

2 Answers2

22

Your best option is probably to pass a Class of the desired enum to the constructor. (See how an EnumMap is constructed for instance.)

You can then use clazz.getEnumConstants() to get hold of the constants.

aioobe
  • 413,195
  • 112
  • 811
  • 826
3

Your first code snippet doesn't work because of how Generics is implemented in Java, and due to a phenomenon known as type erasure. Because of this, the JVM will have no idea what the type of E is when your program is executing.

You could probably do something like this in MyClass's constructor:

public MyClass(E type) {
    choices = type.getDeclaringClass().getEnumConstants();
}
Community
  • 1
  • 1
Jeshurun
  • 22,940
  • 6
  • 79
  • 92