java - JLS:第 5.2 节赋值转换(转换链)

标签 java jls

我正在尝试理解 JLS 的示例。

This section reads :

It is a compile-time error if the chain of conversions contains two parametrized types that are not in the subtype relation.

An example of such an illegal chain would be:

Integer, Comparable<Integer>, Comparable, Comparable<String>

The first three elements of the chain are related by widening reference conversion, while the last entry is derived from its predecessor by unchecked conversion. However, this is not a valid assignment conversion, because the chain contains two parametrized types, Comparable<Integer> and Comparable<String>, that are not subtypes.

我们在什么条件下才能得到这条链?有人可以举一些更详细的例子吗?

最佳答案

我相信我已经明白了一些道理。

赋值上下文适用于赋值表达式。

在表达式中

Integer integerValue = 42;
Comparable<Integer> comparableInteger = integerValue;

整数文字42可以分配给 Integer 类型的变量通过拳击转换。 Integer 类型的值可以分配给 Comparable<Integer> 类型的变量通过扩大引用转换。

在下面的表达式中

Comparable raw = comparableInteger;

Comparable<Integer> 类型的值可以分配给 Comparable 类型的变量通过扩大引用转换。

但是你不能这样做

Comparable<String> comparableString = integerValue;

因为这需要从 Comparable 进行未经检查的转换至Comparable<String> ,这不一定是坏事,除非

the chain of conversions contains two parametrized types that are not in the subtype relation

你本来可以做到的

Comparable raw = comparableInteger;
Comparable<String> parameterized = raw;

这将使用未经检查的转换(当您尝试调用 ClassCastException 时,可能会在运行时使用 compareTo )。但是,在编译时没有问题,因为转换链很简单

Comparable, Comparable<String>

这是允许的。

关于java - JLS:第 5.2 节赋值转换(转换链),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28227967/

相关文章:

java - 使用 findFirst 时,sonarqube Nullpointer 的质量检查失败

java - 检查 dir 存在和 dir contains 在 dropbox api 上不起作用

java - 将 Gradle 添加到 Java 项目 "Exception ... java.lang.NoClassDefFoundError"

java - 将枚举器添加到 Java 枚举中是否会破坏 ABI?

java - 最终字段初始化顺序

Java - 数独(回溯) ' is place valid' 需要方法说明。

java - 声明另一个类的字段是什么意思?

Java 推理 : type variable with an upper bound that is an array type

java - 为什么 Java 中的 try/catch 或 synchronized 需要语句 block ?

java - 为什么我们不能通过未初始化的局部变量访问静态内容?