Enum and generics in Java

I need to provide some funds from enumand generics. Since enums cannot have type parameters (this is simply forbidden by grammar) and actually acts as members public static final, I usually write something like this:

public class GenericEnumLikeClass<T>{

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

    //other things
}

The fact is that I have never done anything like this before and, strictly speaking, I'm not sure of the correctness in terms of Java conventions. Will this be seen as something weird or is it the commmon method used when we need to extend enum-like behavior with Type Paramters?

+4
source share
3 answers

, , Java 1.5 , . API enum. values(), .

+3

@Ingo, value() , :

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

+1

, "" , :

: , , . , , :

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;
    }
}
+1

Source: https://habr.com/ru/post/1613157/


All Articles