JLS:第 5.2 节分配转换(转换链)

JLS: section 5.2 Assignment Conversion (chain of conversions)

我正在尝试理解 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;

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

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

你本来可以做到的

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

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

Comparable, Comparable<String>

这是允许的。