简体   繁体   English

Java中的枚举和泛型

[英]Enum and generics in Java

I need to provide some kind of facilities from enum s and generic s. 我需要提供enumgeneric 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 static final成员一样,我倾向于写这样的东西:

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. 问题是我以前从未做过类似的事情,严格来说,不确定Java公约的正确性。 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 ? 它是否会被视为奇怪的东西,或者当我们需要通过提供Type Paramters来扩展类似enum的行为时使用的通用技术?

This is the technique that was used before Java 1.5 introduced enums, so it does not look strange. 这是在Java 1.5引入枚举之前使用的技术,因此它看起来并不奇怪。 Older APIs have a lot of these enum-style classes. 旧的API有很多这些枚举式的类。 I would recommend to make the constructor private and provide a values() method that returns an array of all available instances. 我建议将构造函数设为私有,并提供一个values()方法,该方法返回所有可用实例的数组。

同意@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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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