简体   繁体   中英

Problem with constructor of a generic class using enumset

I want to develope a class in java. The problem is that the constructor doesn't work

The class is this:

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

//Map
private EnumSet<E> map;

//Constructor
public EnumSetPlus(){

}

I want to inicializate the map with EnumSet.noneOf(E.class) but the constructor gives an error.

Is the constructor wrong?. Can I initialize the variable map without a constructor?.

I have tried public EnumSetPlus<<E extends Enum<E>>> = EnumSet.noneOf(E) in the variable context, but it doesn't work.

I have tried map = EnumSet.noneOf(E.class) into the constructor too, but neither it works.

I think it's a problem with the syntax or with the method

could you help me?

Thanks beforehand!

The problem is that you need a class instance of E which can't be done with just using E or E.class . Try and provide a Class<E> as a constructor parameter, in order to tell the class which enum class it is parameterized for.

This should work:

public EnumSetPlus(Class<E> clazz){
  map = EnumSet.noneOf(clazz);
}

The problem is that the compiler doesn't know of what type E actually is (which enum it is), thus it can't resolve the class at compile time. You need to make that information available at runtime, either with the parameter as suggested or by subclassing EnumSetPlus along with a concrete type parameter which then can be determined using reflection. Since the reflection approach would be overkill in that simple case, I'd suggest trying the parameter approach.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM