Create EnumMap from generic enum

98 Views Asked by At

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?

2

There are 2 best solutions below

0
On BEST ANSWER

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);
  }
}
0
On

You can create a constructor that take a Class<E>, and then use the param to init your map like this:

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

    private Class<E> enumClass;
    
    public SomeClass(Class<E> enumClass) {
        this.enumClass = enumClass;
    }
    
    public void someMethod() {
        Map<E, Long> resultMap = new EnumMap<>(enumClass);
        // .....
    }
}

then you can use your class for example like this:

SomeClass<SomeEnum> someObject = new SomeClass<>(SomeEnum.class);
someObject.someMethod();