为什么不能分配I<?扩展类型>到<类型> ;?? [英] Why can't assign I <? extends Type> to <Type>?
问题描述
以下语句:
URLClassLoader ucl =(URLClassLoader)ClassLoader.getSystemClassLoader();
Class< URLClassLoader> uclc = ucl.getClass();
失败并显示错误:
类型不匹配:无法从Class< capture#2-of?扩展URLClassLoader>到Class< URLClassLoader>
为什么我需要一个演员表,在这里?
我发现了几篇文章解释了为什么你不能做相反的事情(把T分配给a),但这是(明显的)和理解的。
我在月食Luna下编码,所以我不知道它是否是Luna Quirk,或者是否有一些我在泛型中不太了解的东西。
-
类<?扩展URLClassLoader>
为不变。
结果,
> Class <?扩展URLClassLoader>
是不是 Class的子类型
在Java中,变量可以包含相同类型或子类型的实例的引用。
因此,
Class< URLClassLoader> uclc = ucl.getClass();
为无效。
另一方面,
Class <?>扩展URLClassLoader> uclc = ucl.getClass();
将有效。
The following statements:
URLClassLoader ucl = (URLClassLoader) ClassLoader.getSystemClassLoader();
Class<URLClassLoader> uclc = ucl.getClass();
fail with error:
Type mismatch: cannot convert from Class<capture#2-of ? extends URLClassLoader> to Class<URLClassLoader>
Why do I need a cast, here?
I found several posts explaining why You can't do the reverse (assign T to a ), but that's (kind of) obvious and understood.
NOTE: I am coding this under eclipse Luna, so I don't know if it's a Luna Quirk or if there's something I really dont understand in generics.
Covariance vs contravariance vs invariance
Class<? extends URLClassLoader>
is invariant.
As a result,
Class<? extends URLClassLoader>
is not a subtype of Class<URLClassLoader>
In Java a variable can hold a reference of an instance of same type or subtype.
Hence,
Class<URLClassLoader> uclc = ucl.getClass();
is invalid.
On the other hand,
Class<? extends URLClassLoader> uclc = ucl.getClass();
would be valid.
这篇关于为什么不能分配I<?扩展类型>到<类型> ;??的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!