- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我注意到 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
不是原始的 Test
自 repeatPreviousShout()
在“后见之明”中返回 ?
,编译器知道有一个 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/
我是一名优秀的程序员,十分优秀!