문제

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top