Enum 类型的 Java 泛型
我正在尝试编写一个 Java 类,其中一部分需要将未知枚举的值映射到另一个类。我的类包含一个字段 private Map myMap
并使用工厂方法 createMyClass
进行初始化:
public static MyClass <T extends Enum> myClass createMyClass(Class<T> x) {
MyClass theClass = new MyClass() //constructor is private
//...
myMap = new HashMap<T, Unit>();
for(T t : x.getEnumConstants())
myMap.put(t, theClass.new Unit(t));
//...
}
类 Unit
是(并且据我所知必须是)<的内部类代码>我的类。当我将其放入 NetBeans 中时,它会抱怨以下消息:
接口
java.util.Map
中的方法put
不能应用于给定类型
必需:捕获的#4?扩展java.lang.Enum
,MyClass.Unit
发现:T
,MyClass.Unit
我理解(或者至少我认为我理解)集合如何需要非常小心通配符的使用以保持类型安全,但是我无法想象 T extends Enum
为何无法匹配 ?扩展枚举。
I am trying to write a Java class, one part of which requires a mapping of the values of an unknown enum to another class. My class contains a field private Map<? extends Enum, Unit> myMap
and is initialized with a factory method createMyClass
:
public static MyClass <T extends Enum> myClass createMyClass(Class<T> x) {
MyClass theClass = new MyClass() //constructor is private
//...
myMap = new HashMap<T, Unit>();
for(T t : x.getEnumConstants())
myMap.put(t, theClass.new Unit(t));
//...
}
The class Unit
is (and needs to be, as far as I can tell) an inner class of MyClass
. When I put this into NetBeans it complains with this message:
method
put
in interfacejava.util.Map<K,V>
cannot be applied to given types
required: capture #4 of? extends java.lang.Enum
,MyClass.Unit
found:T
,MyClass.Unit
I understand (or at least I think I do) how the Collections need to be very careful about wildcard usage to preserve type safety, but I can't think of how T extends Enum
fails to match ? extends Enum
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试将方法声明更改为:
Try changing your method declaration to:
什么
地图<? extends Enum, Unit>
的意思是“关键是扩展 Enum 的某个特定类,但我不知道是哪一个”。由于您不知道它是哪个类,因此您无法向这样的 Map 添加任何内容,您只能从中获取元素并确定它们是Enum
。您可能应该将该字段声明为
Map
- 它将允许所有Enum
子类。这似乎是对 Java 枚举最常见的误解 - 人们看到
?
通配符并认为他们必须使用它来允许子类。What
Map<? extends Enum, Unit>
means is "The key is some specific class that extends Enum, but I don't known which one". And since you don't know which class it is, you cannot add anything to such a Map, you can only get elements from it and be certain they areEnum
s.You should probably just declare that field as
Map<Enum, Unit>
- it will allow allEnum
subclasses just fine.This seems to be the most common misunderstanding about Java enums by a huge margin - people see that
?
wildcard and think they have to use it to allow subclasses.您可以阅读此泛型教程。它解释了为什么这在第 4 节(通配符)中不起作用。
据我了解,? extends Enum可以是任何枚举,而不仅仅是T或T的子类。
You can read this Generics Tutorial. It explains why this doesn't work in section 4 (Wildcards).
As far as I understand, ? extends Enum can be any enum, not just a T or subclass of T.