在null-reference上创建方法引用不会引发异常 [英] 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.
(我的重点。)
这篇关于在null-reference上创建方法引用不会引发异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!