为什么不能分配I<?扩展类型>到<类型&gt ;?? [英] Why can't assign I <? extends Type> to <Type>?

查看:120
本文介绍了为什么不能分配I<?扩展类型>到<类型&gt ;??的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下语句:

  URLClassLoader ucl =(URLClassLoader)ClassLoader.getSystemClassLoader(); 
Class< URLClassLoader> uclc = ucl.getClass();

失败并显示错误:

 类型不匹配:无法从Class< capture#2-of?扩展URLClassLoader>到Class< URLClassLoader> 

为什么我需要一个演员表,在这里?



我发现了几篇文章解释了为什么你不能做相反的事情(把T分配给a),但这是(明显的)和理解的。

我在月食Luna下编码,所以我不知道它是否是Luna Quirk,或者是否有一些我在泛型中不太了解的东西。

解决方案 div>

协方差与对比与不变性




  • 类<?扩展URLClassLoader> 不变



结果,

>

Class <?扩展URLClassLoader> 不是 Class的子类型< URLClassLoader>






在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&lt;?扩展类型&gt;到&lt;类型&gt ;??的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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