gpt4 book ai didi

java - 通配符类型、类型删除和运行时签名 : what happens on where A and B inherit a common ancestor?

转载 作者:行者123 更新时间:2023-12-01 18:34:55 25 4
gpt4 key购买 nike

(编辑:评论后修复)

让我们采用一个类或接口(interface) A 和一个接口(interface) B,它们都继承一个共同的祖先 X(假设 X 不是对象)。让我们有一个方法,其签名是:

<T extends A & B> void foo(final T arg)

运行时foo的签名是什么?是 void foo(X) 还是 void foo(Object),并且 JVM 在运行时强制转换为 X

最佳答案

类型参数的删除始终是其最左边界的删除,无论继承层次结构中还有哪些其他类( JLS §4.6 )。因此,该方法被删除为:

void foo(final A)

当然,正如注释中所述,如果 AB 都是类,则该代码将无法编译。类型参数边界不能以多个类作为边界,而只能以单个类为边界,后接任意数量的接口(interface)。

参见JLS §4.4类型变量声明的语法:

TypeParameter:
TypeVariable TypeBoundopt

TypeBound:
extends TypeVariable
extends ClassOrInterfaceType AdditionalBoundListopt

AdditionalBoundList:
AdditionalBound AdditionalBoundList
AdditionalBound

AdditionalBound:
& InterfaceType

任何AdditionalBound都应该始终是InterfaceType

the JVM casts to X at runtime?

是的,编译器将添加适当的转换,以便代码按预期工作。

关于java - 通配符类型、类型删除和运行时签名 : what happens on <T extends A & B> where A and B inherit a common ancestor?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22426047/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com