java - 在空引用上创建方法引用不会引发异常

标签 java eclipse nullpointerexception null java-8

为什么可以在一个对象上创建方法引用? Java 中的 null 引用?这样做可能永远不会正确,但会导致以后很难发现的错误:

public class Test {
    void m() {
    }

    public static void main(String[] args) {
        Test test = null;
        Runnable fn = test::m; // no exception
        System.out.println(fn); // prints Test$$Lambda$1/791452441@1c20c684
        fn.run(); // throws a null pointer exception
    }
}

最佳答案

Is there a reason why it is possible to create method references on a null reference in Java?

不是,但显然在这方面 Eclipse 中存在错误(编辑:自 been fixed 以来)。根据规范,当您使用 JDK 的工具时,它会失败并在 Runnable fn = test::m; 行出现 NPE。

证明:http://ideone.com/APWXna (或者使用 javacjava 而不是 Eclipse 在本地编译和运行它)

理论:来自JLS §15.13.3 :

First, if the method reference expression begins with an ExpressionName or a Primary, this subexpression is evaluated. If the subexpression evaluates to null, a NullPointerException is raised, and the method reference expression completes abruptly.

(我的重点。)

关于java - 在空引用上创建方法引用不会引发异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37681625/

相关文章:

java - 如何在 Java 中使用控制台运行另一个 Java 进程(在 Linux 中)

java - 在一个 List<String> 中添加两个 List<String>

eclipse - Grails编译器不匹配

java - 如何修复代码中的空指针异常?

java - 获取异常对象的错误号

java - ListView 可以在 Android 中有两种或多种不同类型的行布局吗?

java - 将日期从 20160729161455 转换为 29/07/2016 16 :14:55

java - Birt 布局中缺少预览选项卡

java - 为什么在 Eclipse 中创建 Servlet 会破坏我的 web.xml?

java - 将非空键和值放入哈希表时出现 NullPointerException