在null-reference上创建方法引用不会引发异常 [英] Creating a method reference on a null-reference does not throw an exception

查看:100
本文介绍了在null-reference上创建方法引用不会引发异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能在Java中使用
null 引用创建方法引用?这样做可能永远不会正确但可能导致以后很难找到的错误:

Is there a reason why it is possible to create method references on a null reference in Java? Doing this is probably never correct but can result in errors which are hard to find later:

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
    }
}


推荐答案


为什么有可能在Java中的 null 引用上创建方法引用?

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

它不是,但显然Eclipse中存在这方面的错误(编辑:已有自已修复)。根据规范,当您使用JDK的工具时,它在 Runnable fn = test :: m; 行上的NPE失败。

It isn't, but apparently there's a bug in Eclipse in this regard (edit: which has since been fixed). According to the specification, and when you use the JDK's tools, it fails with an NPE on the Runnable fn = test::m; line.

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

Proof: http://ideone.com/APWXna (or compile and run it locally with javac and java rather than Eclipse)

理论:来自JLS§ 15.13.3


首先,如果方法引用表达式以 ExpressionName 开头或者 Primary ,评估此子表达式。 如果子表达式求值为 null ,则会引发 NullPointerException ,并且方法引用表达式突然完成。

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.

(我的重点。)

这篇关于在null-reference上创建方法引用不会引发异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆