java - 在 java 7 中编译的代码在 Java 8 中无法编译。请提供解释

标签 java java-8 type-inference

为什么以下代码在 Java 8 中无法编译。 我知道类型推断是这里的罪魁祸首,但我想得到一个解释。

public class TypeInferenceProblem {

    class ATest<E extends B>
    {

        private E find(C<? extends E> CObj)
        {
            return null;
        }

        public void findCs(List<? extends C<? extends E>> cList)
        {

            find(new C());// This compiles fine
            for (C cObj : cList)
                {
                    E cachedEntity = find(cObj); // This cause error in java 8 but works fine in java 7
                }
        }
    }

     class B{
     }

     class C <T> {
     }
}

最佳答案

只是为了明确引用 Holger 的正确评论:

在 JLS 8 中,这是在 §18.5.2 中确定的,其中包含这句话(在第六个主要项目符号内):

If unchecked conversion was necessary for the method to be applicable during constraint set reduction in §18.5.1, then the parameter types of the invocation type of m are obtained by applying θ' to the parameter types of m's type, and the return type and thrown types of the invocation type of m are given by the erasure of the return type and thrown types of m's type.

我突出显示了相关部分。

类似的句子已经出现在 JLS 7 §15.12.2.6 中:

Otherwise, if unchecked conversion was necessary for the method to be applicable, then the result type is the erasure (§4.6) of the method's declared return type.

两个版本都相当于定义使用原始类型参数(需要未经检查的转换)调用 find(..) 具有通过删除声明的返回类型获得的返回类型EB

如果 Java 7 的编译器没有报告此错误,那么这是一个错误。

关于java - 在 java 7 中编译的代码在 Java 8 中无法编译。请提供解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40800399/

相关文章:

Scala 类型推断和多参数列表

使用 _ 占位符的 scala 类型推断

java - 如何在 webdriver 中使用具有 SearchContext 、 By 作为参数的方法

java - android AES/CTR/NoPadding 中的解密和密码问题

java - 关闭流而不将其分配给变量 [Java]

java - Java 8 日期时间 API (java.time) 和 Joda-Time 之间的差异

Java转换整数到字符串不一致

java - 需要一些管理字符串的帮助

java - 使用 Java8 Streams 时是否可以获取 ArrayList<Object> 的索引?

java - 如何在类定义中的泛型类型中捕获子类型?