gpt4 book ai didi

java - 为什么 Java 7 菱形运算符不能与匿名类一起使用?

转载 作者:IT老高 更新时间:2023-10-28 20:54:08 25 4
gpt4 key购买 nike

考虑这个试图实例化一些 Lists 的 Java 代码:

List<String> list1 = new ArrayList<String>();
List<String> list2 = new ArrayList<>();
List<String> list3 = new ArrayList<String>() { };
List<String> list4 = new ArrayList<>() { };
List<String> list5 = new ArrayList<Integer>() { };

list1list2 很简单; list2 使用 Java 7 中新的菱形运算符来减少类型参数的不必要重复。

list3list1 的变体,使用匿名类,可能会覆盖 ArrayList 的某些方法。

list4 尝试使用菱形运算符,类似于 list2,但这是一个编译错误,并显示消息 '<>' cannot be used with匿名类

list5 产生一个错误,证明编译器知道实际需要什么类型。错误消息是 Type mismatch: cannot convert from new ArrayList (){} to List

那么,有了list4的声明,为什么菱形运算符不能和匿名类一起使用呢?有一个similar question here接受的答案包含来自 JSR-334 的以下解释:

Using diamond with anonymous inner classes is not supported since doing so in general would require extensions to the class file signature attribute to represent non-denotable types, a de facto JVM change.

我需要一些帮助来理解这个推理。为什么显式类型与相同且显然很容易推断的类型需要在生成的类文件中存在任何差异? “一般情况下”会涵盖哪些困难的用例?

造成这种情况的根本原因是什么?

最佳答案

这已在 the "Project Coin" mailing list 上讨论过.实质上(强调我的):

Internally, a Java compiler operates over a richer set of types than those that can be written down explicitly in a Java program. The compiler-internal types which cannot be written in a Java program are called non-denotable types. Non-denotable types can occur as the result of the inference used by diamond. Therefore, using diamond with anonymous inner classes is not supported since doing so in general would require extensions to the class file signature attribute to represent non-denotable types, a de facto JVM change. It is feasible that future platform versions could allow use of diamond when creating an anonymous inner class as long as the inferred type was denotable.

请注意,Java 8 也不支持它,但将作为新功能包含在 Java 9 中("Milling Project Coin" 的第 3 项)。

关于java - 为什么 Java 7 菱形运算符不能与匿名类一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22200647/

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