gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 03:46:41 25 4
gpt4 key购买 nike

为什么可以在一个对象上创建方法引用?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/48979486/

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