简体   繁体   中英

Enum and generics in Java

I need to provide some kind of facilities from enum s and generic s. 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 ?

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.

同意@Ingo,你可以使用它作为构造函数并提供一个value()方法,就像:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM