theblitz
theblitz

Reputation: 6881

Get list of Enums from generic class

I have a class that is paramaterised with an extend of Enum.

public class MyClass<EnumType extends Enum> { 

  public MyClass(){
    Enum<?>[] enums = EnumType.getEnumConstants();
  }

}

The line:

Enum<?>[] enums = EnumType.getEnumConstants()

fails to compile with "can not resolve method".

How can I get to the base type and get the enums?

OTOH, if I do the following it works ok:

public void setEnumType(Class <? extends Enum> clazz){
   Enum<?>[] enums = clazz.getEnumConstants();
}

I can't pass this into the constructor as it is a custom view which is directly inserted in the parent.

Upvotes: 1

Views: 38

Answers (1)

Andy Turner
Andy Turner

Reputation: 140318

Owing to erasure, you have to pass an instance of the enum class to the constructor:

public class MyClass<EnumType extends Enum<EnumType>> { 
                                       // ^ don't forget this    
  public MyClass(Class<EnumType> c){
    Enum<?>[] enums = c.getEnumConstants();
  }

}

MyClass<YourEnum> m = new MyClass<>(YourEnum.class);

Or, you could pass YourEnum.values() directly. The risk there is that a caller can pass any array, not necessarily one with all values, without duplicates, in the right order etc.

Upvotes: 1

Related Questions