如何使用泛型实现枚举? [英] How to implement enum with generics?

查看:67
本文介绍了如何使用泛型实现枚举?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的通用接口:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆