如何使用泛型实现枚举?

编程入门 行业动态 更新时间:2024-10-27 06:34:00
本文介绍了如何使用泛型实现枚举?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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.

更多推荐

如何使用泛型实现枚举?

本文发布于:2023-11-16 17:29:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1606358.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!