Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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). Of course I could define different Enums for every ClassX, but this is not really what I want.

like image 641
icvg Avatar asked Aug 24 '12 16:08

icvg


2 Answers

JLS does not allow type parameters for an enum:

EnumDeclaration:
    ClassModifiers(opt) enum Identifier Interfaces(opt) EnumBody

EnumBody:
    { EnumConstants(opt) ,(opt) EnumBodyDeclarations(opt) }
like image 53
dcernahoschi Avatar answered Sep 25 '22 23:09

dcernahoschi


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

like image 21
Alex Coleman Avatar answered Sep 23 '22 23:09

Alex Coleman