Creating a class with a generic enum field. Enum field used to get the enumeration values

advertisements

I need Class to which I can give different enum types and in this class I need to obtain all values of the given enum.

This is how I tried to do, but I have an issue defining the type of the enum field:

class MyClass{
  private Class<T> enumType; //how to say who is T?

  void <T extends Enum<T>> setEnumType(Class<T> enumType){
     this.enumType = enumType;
  }

  void doSomething(){
     for (Enum<T> literal : enumType.getEnumConstants()) {
         // do something with literal.name();
     }
  }
}

Update: I can't make the class generic (MyClass<T extends Enum<T>>). So I need other solution.


Something like this should work (however I would suggest to pass the enum class in the constructor):

class MyClass<T extends Enum<T>> {
  private Class<T> enumType; 

  void setEnumType(Class<T> enumType){
     this.enumType = enumType;
  }

  void doSomething(){
     for (T literal : enumType.getEnumConstants()) {
         // do something with literal.name();
     }
  }
}