[英]Java generics for Enum types
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.我正在尝试编写 Java class,其中一部分需要将未知枚举的值映射到另一个 class。 My class contains a field
private Map<? extends Enum, Unit> myMap
我的 class 包含一个字段
private Map<? extends Enum, Unit> myMap
private Map<? extends Enum, Unit> myMap
and is initialized with a factory method createMyClass
: private Map<? extends Enum, Unit> 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));
//...
}
The class Unit
is (and needs to be, as far as I can tell) an inner class of MyClass
. class
Unit
是(据我所知,必须是) MyClass
的内部 class 。 When I put this into NetBeans it complains with this message:当我将它放入 NetBeans 时,它会抱怨以下消息:
method
put
in interfacejava.util.Map<K,V>
cannot be applied to given types接口
put
java.util.Map<K,V>
中的方法不能应用于给定类型
required: capture #4 of? extends java.lang.Enum
必需:捕获#4 of
? extends java.lang.Enum
? extends java.lang.Enum
,MyClass.Unit
? extends java.lang.Enum
,MyClass.Unit
found:T
,MyClass.Unit
找到:
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
我了解(或至少我认为我了解)Collections 需要非常小心通配符的使用以保持类型安全,但我想不出
T extends Enum
无法匹配? extends Enum
? extends Enum
. ? extends Enum
。
Try changing your method declaration to:尝试将您的方法声明更改为:
public static <T extends Enum<T>> MyClass createMyClass(Class<T> x) {
}
You can read this Generics Tutorial .您可以阅读此Generics 教程。 It explains why this doesn't work in section 4 (Wildcards).
它解释了为什么这在第 4 节(通配符)中不起作用。
As far as I understand, ?据我了解, ? extends Enum can be any enum, not just a T or subclass of T.
extends Enum可以是任何枚举,而不仅仅是T或 T 的子类。
What Map<? extends Enum, Unit>
什么
Map<? extends Enum, Unit>
Map<? extends Enum, Unit>
means is "The key is some specific class that extends Enum, but I don't known which one". Map<? extends Enum, Unit>
的意思是“关键是一些扩展 Enum 的特定 class,但我不知道是哪一个”。 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 are Enum
s.而且由于您不知道它是哪个 class ,因此您不能向这样的 Map 添加任何内容,您只能从中获取元素并确定它们是
Enum
。
You should probably just declare that field as Map<Enum, Unit>
- it will allow all Enum
subclasses just fine.您可能应该将该字段声明为
Map<Enum, Unit>
- 它允许所有Enum
子类就好了。
This seems to be the most common misunderstanding about Java enums by a huge margin - people see that ?
这似乎是关于 Java 枚举的最常见误解——人们看到了
?
wildcard and think they have to use it to allow subclasses.通配符并认为他们必须使用它来允许子类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.