我有一个像这样的通用接口:
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.
更多推荐
如何使用泛型实现枚举?
发布评论