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 ?
Your best option is probably to pass a
Classof the desired enum to the constructor. (See how anEnumMapis constructed for instance.)You can then use
clazz.getEnumConstants()to get hold of the constants.