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

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

问题描述

以下陈述:

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

因错误而失败:

Type mismatch: cannot convert from Class<capture#2-of ? extends URLClassLoader> to Class<URLClassLoader>

这里为什么需要演员表?

Why do I need a cast, here?

我发现了几篇文章解释了为什么你不能做相反的事情(将 T 分配给 a ),但这(有点)显而易见并且可以理解.

I found several posts explaining why You can't do the reverse (assign T to a ), but that's (kind of) obvious and understood.

注意:我是在 eclipse Luna 下编写的,所以我不知道这是 Luna 的怪癖还是我真的不理解泛型.

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.

推荐答案

协变 vs 逆变 vs 不变

  • 不变的.

因此,

不是 Class<URLClassLoader>

在 Java 中,变量可以保存对相同类型或子类型的实例的引用.

In Java a variable can hold a reference of an instance of same type or subtype.

因此,

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

无效.

另一方面,

Class<? extends URLClassLoader> uclc = ucl.getClass();

将是有效.

这篇关于为什么不能分配 I &lt;?扩展类型>到&lt;类型&gt;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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