St.Antario
St.Antario

Reputation: 27385

Enum and generics in Java

I need to provide some kind of facilities from enums and generics. Since enums cannot have type parameters (it's just forbidden by the grammar) and actually acts like public static final members I tend to write something like this:

public class GenericEnumLikeClass<T>{

    public static GenericEnumLikeClass<MyType> TYPE_INSTANCE;
    public static GenericEnumLikeClass<AnotherType> ANOTHER_INSTANCE;

    //other things
}

The thing is I've never done something similar before and strictly speaking not sure about the correctness from the Java Conventions standpoint. Will it be considered as something strange or it's a commmon technique used when we need to extend enum-like behavior with providing Type Paramters?

Upvotes: 4

Views: 152

Answers (3)

fluminis
fluminis

Reputation: 4059

Don't know exactly what you want to do with your 'generic' argument, but this could give you some ideas:

Edit: As you don't explain how you use this generic parameter I could not give real example. Just add some methods, to explain what I have in mind:

public enum MyGenericEnum {

    TYPE_INSTANCE(MyClass.class),
    ANOTHER_INSTANCE(AnotherClass.class);

    private Class<? extends SomeSuperClass> clazz;

    private MyGenericEnum(Class<? extends SomeSuperClass> clazz) {
        this.clazz = clazz;
    }

    public Class<? extends SomeSuperClass> getType() {
        return clazz;
    }

    @SuppressWarnings("unchecked")
    public <T extends SomeSuperClass> T getObject() {
        try {
            return (T) clazz.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }
}

Upvotes: 1

Soven K Rout
Soven K Rout

Reputation: 135

Agreed with @Ingo, you can use as constructor and provide a value() method just like:

public enum GenericEnumLikeClass { MyType("TYPE_INSTANCE"), AnotherType("ANOTHER_INSTANCE");

Upvotes: 1

Ingo Kegel
Ingo Kegel

Reputation: 48005

This is the technique that was used before Java 1.5 introduced enums, so it does not look strange. Older APIs have a lot of these enum-style classes. I would recommend to make the constructor private and provide a values() method that returns an array of all available instances.

Upvotes: 3

Related Questions