在空引用上创建方法引用不会引发异常 [英] Creating a method reference on a null-reference does not throw an exception
问题描述
为什么可以在一个对象上创建方法引用?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
, aNullPointerException
is raised, and the method reference expression completes abruptly.
(我的重点.)
这篇关于在空引用上创建方法引用不会引发异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!