如何用泛型实现枚举? [英] How to implement enum with generics?
问题描述
我有一个这样的通用界面:
I have a generic interface like this:
interface A<T> {
T getValue();
}
此接口有限的实例,因此最好将它们实现为枚举值。问题是这些实例具有不同类型的值,所以我尝试了以下方法,但是它不编译:
This interface has limited instances, hence it would be best to implement them as enum values. The problem is those instances have different type of values, so I tried the following approach but it does not compile:
public enum B implements A {
A1<String> {
@Override
public String getValue() {
return "value";
}
},
A2<Integer> {
@Override
public Integer getValue() {
return 0;
}
};
}
任何关于这个想法?
推荐答案
你不能。 Java不允许在枚举常量上使用通用类型。枚举类型允许使用枚举类型:
You can't. Java doesn't allow generic types on enum constants. They are allowed on enum types, though:
public enum B implements A<String> {
A1, A2;
}
在这种情况下你可以做的是每个通用的枚举类型类型,或'假的'有一个枚举,只是使它成为一个类:
What you could do in this case is either have an enum type for each generic type, or 'fake' having an enum by just making it a class:
public class B<T> implements A<T> {
public static final B<String> A1 = new B<String>();
public static final B<Integer> A2 = new B<Integer>();
private B() {};
}
不幸的是,他们都有缺点。
Unfortunately, they both have drawbacks.
这篇关于如何用泛型实现枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!