我想了解捕获的转换如何适用于通配符类型。 JLS里面有一段解释说:
Let
G
name a generic type declaration (§8.1.2, §9.1.2) withn
type parametersA1,...,An
with corresponding boundsU1,...,Un
.There exists a capture conversion from a parameterized type
G<T1,...,Tn>
(§4.5) to a parameterized typeG<S1,...,Sn>
, where, for1 ≤ i ≤ n
:
If
Ti
is a wildcard type argument (§4.5.1) of the form?
, thenSi
is a fresh type variable whose upper bound isUi[A1:=S1,...,An:=Sn]
and whose lower bound is thenull
type (§4.1).If
Ti
is a wildcard type argument of the form? extends Bi
, thenSi
is a fresh type variable whose upper bound isglb(Bi, Ui[A1:=S1,...,An:=Sn])
and whose lower bound is thenull
type.
glb(V1,...,Vm)
is defined asV1 & ... & Vm
.It is a compile-time error if, for any two classes (not interfaces)
Vi
andVj
,Vi
is not a subclass ofVj
or vice versa.If
Ti
is a wildcard type argument of the form? super Bi
, thenSi
is a fresh type variable whose upper bound isUi[A1:=S1,...,An:=Sn]
and whose lower bound isBi
.Otherwise,
Si = Ti
.
我不清楚的是Ui[A1:=S1,...,An:=Sn]
.这是什么意思?我找不到通过 JLS 搜索的定义。
最佳答案
首先:定义替换。
[A<sub>1</sub>:=S<sub>1</sub>,...,A<sub>n</sub>:=S<sub>n</sub>]
是 substitution in JLS notation (§1.3) ,定义为:
The notation
[F<sub>1</sub>:=T<sub>1</sub>,...,F<sub>n</sub>:=T<sub>n</sub>]
denotes substitution ofF<sub>i</sub>
byT<sub>i</sub>
for1 ≤ i ≤ n
.
声明:[A<sub>1</sub>:=S<sub>1</sub>,...,A<sub>n</sub>:=S<sub>n</sub>]
是类型参数(属于G
)A<sub>i</sub>
的替换按类型变量 S<sub>i</sub>
对于 1 ≤ i ≤ n
. (另见脚注 †)
下一步:考虑为什么我们可能需要在第一种情况下进行替换。来自 §5.1.10 (突出显示添加到下一个点):
Let
G
name a generic type declaration ... withn
type parametersA<sub>1</sub>,...,A<sub>n</sub>
with corresponding boundsU<sub>1</sub>,...,U<sub>n</sub>
.
即:
- 界限
U<sub>1</sub>,...,U<sub>n</sub>
具体对应类型参数A<sub>1</sub>,...,A<sub>n</sub>
. - 未说明的推论:边界
U<sub>1</sub>,...,U<sub>n</sub>
不对应类型变量S<sub>1</sub>,...,S<sub>n</sub>
.
放在一起:我现在说的是显而易见的,因为我确信你领先于我,但是......
关于“ T<sub>i</sub>
是一个通配符类型参数 ... 形式为 ?
”的规则
S<sub>i</sub>
is a fresh type variable whose upper bound isU<sub>i</sub> [A<sub>1</sub>:=S<sub>1</sub>,...,A<sub>n</sub>:=S<sub>n</sub>]
-
S<sub>i</sub>
是新类型变量 - 其上限为
U<sub>i</sub>
- 哪里(这是隐含位)
- 类型参数
A<sub>1</sub>,...,A<sub>n</sub>
那U<sub>1</sub>,...,U<sub>n</sub>
具体对应 - 已被类型变量
S<sub>1</sub>,...,S<sub>n</sub>
替代 - 制作
U<sub>1</sub>,...,U<sub>n</sub>
对应于类型变量S<sub>1</sub>,...,S<sub>n</sub>
长话短说
即这只是意味着原来的上限U<sub>i</sub>
也是 S<sub>i</sub>
的上限
脚注
† 有助于记忆from the JLS类型变量和类型参数不是一回事(因此我们可以开始明白为什么我们需要替换):
A type variable is an unqualified identifier used as a type in class, interface, method, and constructor bodies.
A type variable is introduced by the declaration of a type parameter of a generic class, interface, method, or constructor.
关于java - 了解捕获的转化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31206947/