corgrath
corgrath

Reputation: 12293

Is it possible to add generics to enum values? Example pseudo-code included

Is it possible to add generics to enum values?

Something similar to this pseudo code:

    public enum MyEnum<T> {

            VALUE1<String>,
            VALUE2<Boolean>;

            public T get() {
                    return (T) AnotherSystem.get(this); // Where AnotherSystem.get returns an Object
            }

    }

Have I just written this incorrectly, or is this not possible at all?

What other options do I have to make get() return a specific generic type (T)

Upvotes: 1

Views: 425

Answers (2)

irreputable
irreputable

Reputation: 45463

You can do

        public <T> T get() {
                return (T) AnotherSystem.get(this); 
        }

If you need to associate a type with an enum, it can be a property

public enum MyEnum {

    VALUE1(String.class),
    VALUE2(Boolean.class);

    public final Class<?> type;
    MyEnum(Class<?> type){ this.type = type; }

    public <T> T get() {
        return (T) AnotherSystem.get(this, this.type);
    }

}

class AnotherSystem
{
    static<T> T get(MyEnum e, Class<T> type){ return null; }
}

Upvotes: 4

Jon Skeet
Jon Skeet

Reputation: 1504172

No, I don't believe anything like this is possible. If you look at section 8.9 of the JLS, where enum declarations are specified, there's nothing about generics there:

Compare it with the "normal" class declaration in section 8.1, where part of the spec is the type parameters involved.

Upvotes: 1

Related Questions