存储枚举类引用

时间:2014-06-27 08:23:24

标签: java generics enums wildcard

好的,我有两个枚举:

    public enum AnotherEnum
    {
        value1, value2, value3;
    }

    public enum MyEnum implements MyInterface
    {
        value1(AnotherEnum);

        generic_reference_type a;

        MyEnum ( ?? )
        {
            a = ??
        }

        GetGenericReference()
        {
            return this.a;
        }
    }

我希望MyEnum存储对AnotherEnum类的引用,以便我能够执行此操作:

    MyEnum.value1.GetGenericReference().values();

这可能吗?

2 个答案:

答案 0 :(得分:1)

如果您不了解该课程,您将获得带有反射的通用枚举值

Object someEnum = ...
// get all the values for the same Enum type.
Object[] enums = someEnum.getClass().getEnumConstants()

答案 1 :(得分:1)

如果我正确地阅读你的问题。你想将不同的泛型类型传递给枚举的每个实例......你不能这样做,因为枚举的每个实例都来自相同的 class,可以是通用的,但如果泛型必须具有相同的泛型参数。

但是,您可以将代码置于枚举的基础上,以表达为Class<? extends Enum<?>>来表达您的意图:

public enum AnotherEnum {
    A, B, C;
}

public enum YetAnotherEnum {
    X, Y, Z;
}

public interface MyInterface {
    public Enum<?>[] getGenericReferenceValues();
}

public enum MyEnum implements MyInterface {
    value1(AnotherEnum.class),
    value2(YetAnotherEnum.class);

    final Class<? extends Enum<?>> a;

    private MyEnum(Class<? extends Enum<?>> a) {
        this.a = a;
    }

    public Enum<?>[] getGenericReferenceValues() {
        return a.getEnumConstants();
    }
}

看到它有效:

public static void main(String[] args) {
    System.out.println(Arrays.toString(MyEnum.value1.getGenericReferenceValues()));
    System.out.println(Arrays.toString(MyEnum.value2.getGenericReferenceValues()));
}

输出:

[A, B, C]
[X, Y, Z]
相关问题