开发者

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜