Search code examples
javagenericsenumsenum-map

Create EnumMap from generic enum


I have a class parametrized with generic enum, like this:

public class SomeClass<E extends Enum<E>> {
  public void someMethod( ) {
    // I want to initiate a map like this:
    Map<E, Long> resultMap = new EnumMap<>(E.class);
    //.....
  }
}

However, the EnumMap constructor says the following error: "Cannot access class object of a type parameter".

What is the right way to initialize EnumMap in this case?


Solution

  • It's not possible to use E.class. You need to save the class instance somehow - since the class is generic, instance variable is good choice, and then instantiate the map using the instance variable as parameter.

    public class SomeClass<E extends Enum<E>> {
    
      private final Class<E> clazz;
    
      public SomeClass(Class<E> clazz) {
        this.clazz = clazz;
      }
    
      public void someMethod() {
        Map<E, Long> resultMap = new EnumMap<>(this.clazz);
      }
    }