gpt4 book ai didi

java - 什么是 Java 中的捕获转换,谁能给我举个例子?

转载 作者:太空狗 更新时间:2023-10-29 22:54:08 24 4
gpt4 key购买 nike

我注意到 JLS 谈到了 5.1.10 Capture Conversion , 但我不明白它们是什么。

谁能给我解释一下/举个例子?

最佳答案

捕获转换旨在制作通配符(在泛型中),?有用。

假设我们有以下类:

public interface Test<T> {
public void shout(T whatever);
public T repeatPreviousShout();

}

在我们代码的某处,

public static void instantTest(Test<?> test) {
System.out.println(test.repeatPreviousShout());
}

因为 test不是原始的 TestrepeatPreviousShout()在“后见之明”中返回 ? ,编译器知道有一个 T作为 Test 的类型参数.这T是一些未知的 T所以编译器删除未知类型(对于通配符,它​​替换为 Object ),因此 repeatPreviousShout()返回 Object .

但如果我们有,

public static void instantTest2(Test<?> test) {
test.shout(test.repeatPreviousShout());
}

编译器会给我们一个类似于Test<capture#xxx of ?> cannot be applied的错误。 (其中 xxx 是一个数字,例如 337 )。

这是因为编译器试图对 shout() 进行类型安全检查但由于它收到了一个通配符,它​​不知道是什么 T表示,因此它创建了一个名为capture of 的占位符。

来自 here (Java theory and practice: Going wild with generics, Part 1) ,它明确指出:

Capture conversion is what allows the compiler to manufacture a placeholder type name for the captured wildcard, so that type inference can infer it to be that type.

希望对你有帮助。

关于java - 什么是 Java 中的捕获转换,谁能给我举个例子?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4431702/

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