Reputation: 197
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). Of course I could define different Enums for every ClassX, but this is not really what I want.
Upvotes: 6
Views: 575
Reputation: 533492
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.
Upvotes: 1
Reputation: 15230
JLS does not allow type parameters for an enum:
EnumDeclaration:
ClassModifiers(opt) enum Identifier Interfaces(opt) EnumBody
EnumBody:
{ EnumConstants(opt) ,(opt) EnumBodyDeclarations(opt) }
Upvotes: 6
Reputation: 7326
Enum's can in fact have fields, and it looks like that is what you want:
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
Upvotes: 1