什么是Java中的捕获转换,谁能给我举例? [英] What is a capture conversion in Java and can anyone give me examples?
问题描述
我注意到JLS谈到了 5.1 .10捕获转换,但我不明白它们是什么。
I've noticed JLS talks of 5.1.10 Capture Conversion, but I fail to understand what they are.
任何人都可以向我解释/给出示例吗?
Can anyone explain them to me/give examples?
推荐答案
捕获转换旨在使通配符(在泛型中),?
有用。
Capture conversion was designed to make wildcards (in generics), ?
useful.
假设我们有以下类:
public interface Test<T> {
public void shout(T whatever);
public T repeatPreviousShout();
}
以及我们的代码中的某处,
and somewhere on our code we have,
public static void instantTest(Test<?> test) {
System.out.println(test.repeatPreviousShout());
}
因为 test
是不是原始的测试
,而且hindsight中的 repeatPreviousShout()
会返回?
,编译器知道有 T
作为 Test
的类型参数。
这个 T
是针对某些未知的 T
所以编译器会删除未知类型(对于通配符,它会替换它)使用 Object
)。因此 repeatPreviousShout()
返回对象
。
Because test
is not a raw Test
and since repeatPreviousShout()
in "hindsight" returns a ?
, the compiler knows that there's a T
that serves as a type parameter for Test
.
This T
is for some unknown T
so the compiler erases the unknown type (for wildcard, it replaces with Object
)., hence repeatPreviousShout()
returns an Object
.
但如果我们有,
public static void instantTest2(Test<?> test) {
test.shout(test.repeatPreviousShout());
}
编译器会给我们一个类似的错误测试<捕获#xxx?>无法应用
(其中 xxx
是一个数字,例如 337
)。
The compiler would give us an error of something like Test<capture#xxx of ?> cannot be applied
(where xxx
is a number, e.g. 337
).
这是因为编译器尝试对 shout()
进行类型安全检查,但由于它收到了通配符,因此它没有不知道 T
代表什么,因此它会创建一个名为捕获的占位符。
This is because the compiler tries to do the type safety check on shout()
but since it received a wildcard, it doesn't know what T
represents, hence it creates a placeholder called capture of.
从这里(Java理论与实践:与泛型一起疯狂,第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.
希望这会对你有所帮助。
Hope this helps you.
这篇关于什么是Java中的捕获转换,谁能给我举例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!