6

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.

1
  • Enums cannot be parameterized this way as dcernahoschi points out. If you could expand your question to include what you're looking to achieve with the classes calling this Enum, that would be helpful. Commented Aug 24, 2012 at 16:21

3 Answers 3

6

JLS does not allow type parameters for an enum:

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

EnumBody:
    { EnumConstants(opt) ,(opt) EnumBodyDeclarations(opt) }
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.