[英]Java Enums values with Generics
I need something like this: 我需要这样的东西:
public enum Enum {
ENUM1<Class1>(Class1.class, "A DESCRIPTION", new Class1()),
ENUM2<Class2>(Class2.class, "A DESCRIPTION", new Class2()),
ENUM3<Class3>(Class3.class, "A DESCRIPTION", new Class3());
private Enum(Class<? extends Object> clazz, String description, Object instance) {}
}
What I need: a single place where I define different instances of all ClassX (they extend the same ClassSuper). 我需要的是:我在一个地方定义所有ClassX的不同实例(它们扩展了相同的ClassSuper)。 Of course I could define different Enums for every ClassX, but this is not really what I want.
当然,我可以为每个ClassX定义不同的枚举,但这不是我想要的。
JLS does not allow type parameters for an enum: JLS不允许枚举的类型参数:
EnumDeclaration:
ClassModifiers(opt) enum Identifier Interfaces(opt) EnumBody
EnumBody:
{ EnumConstants(opt) ,(opt) EnumBodyDeclarations(opt) }
Enum's can in fact have fields, and it looks like that is what you want: 事实上,Enum可以有字段,看起来就像你想要的那样:
private Object instance;
private Enum(Class<? extends Object> clazz, String description, Object instance) {
this.instance=instance;
}
public Object getInstance() {
return instance;
}
As far as I can tell, enums cant be paramitized though, so you cant have that in your code. 据我所知,枚举不能被删除,所以你不能在你的代码中使用它。 What exactly are you trying to do with these classes though?
你究竟想要对这些课程做些什么呢? I may be misunderstanding your question
我可能误解了你的问题
You can write the following to hold all the same information (as the class can be obtained from the class) 您可以编写以下内容来保存所有相同的信息(因为该类可以从类中获取)
public enum Enum {
ENUM1("A DESCRIPTION", new Class1()),
ENUM2("A DESCRIPTION", new Class2()),
ENUM3("A DESCRIPTION", new Class3());
private Enum(String description, Object instance) {}
}
The problem you will find is that with enums, generics are not as useful and you can write much the same behaviour without generics. 你会发现问题是,使用枚举,泛型不是那么有用,你可以在没有泛型的情况下编写相同的行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.