我想用java开发一个类。问题是构造函数不起作用
该类是这样的:
public class EnumSetPlus<E extends Enum<E>> {
//Map
private EnumSet<E> map;
//Constructor
public EnumSetPlus(){
}
我想用 EnumSet.noneOf(E.class)
初始化地图,但构造函数给出错误。
构造函数错了吗?我可以在没有构造函数的情况下初始化变量映射吗?
我已经尝试过 public EnumSetPlus<>>> = EnumSet.noneOf(E) 在变量上下文中,但它不起作用。
我也尝试过在构造函数中使用 map = EnumSet.noneOf(E.class)
,但都不起作用。
我认为这是语法或方法的问题,
你能帮我吗?
预先感谢!
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!
发布评论
评论(1)
问题是您需要一个
E
的类实例,而仅使用E
或E.class
是无法完成的。尝试提供一个Class
作为构造函数参数,以便告诉该类它被参数化为哪个枚举类。这应该可行:
问题是编译器不知道 E 实际上是什么类型(它是哪个枚举),因此它无法在编译时解析该类。您需要在运行时提供该信息,可以使用建议的参数,也可以通过子类化
EnumSetPlus
以及具体的类型参数(然后可以使用反射来确定)。由于反射方法在这种简单的情况下会显得太过分,因此我建议尝试参数方法。The problem is that you need a class instance of
E
which can't be done with just usingE
orE.class
. Try and provide aClass<E>
as a constructor parameter, in order to tell the class which enum class it is parameterized for.This should work:
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.