为什么不能分配 I <?扩展类型>到<类型>?

2023-04-06Java开发问题
1

本文介绍了为什么不能分配 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;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

如何使用 JAVA 向 COM PORT 发送数据?
How to send data to COM PORT using JAVA?(如何使用 JAVA 向 COM PORT 发送数据?)...
2024-08-25 Java开发问题
21

如何使报表页面方向更改为“rtl"?
How to make a report page direction to change to quot;rtlquot;?(如何使报表页面方向更改为“rtl?)...
2024-08-25 Java开发问题
19

在 Eclipse 项目中使用西里尔文 .properties 文件
Use cyrillic .properties file in eclipse project(在 Eclipse 项目中使用西里尔文 .properties 文件)...
2024-08-25 Java开发问题
18

有没有办法在 Java 中检测 RTL 语言?
Is there any way to detect an RTL language in Java?(有没有办法在 Java 中检测 RTL 语言?)...
2024-08-25 Java开发问题
11

如何在 Java 中从 DB 加载资源包消息?
How to load resource bundle messages from DB in Java?(如何在 Java 中从 DB 加载资源包消息?)...
2024-08-25 Java开发问题
13

如何更改 Java 中的默认语言环境设置以使其保持一致?
How do I change the default locale settings in Java to make them consistent?(如何更改 Java 中的默认语言环境设置以使其保持一致?)...
2024-08-25 Java开发问题
13