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
}
}
Is there a reason why it is possible to create method references on a
null
reference in Java?
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.
Proof: http://ideone.com/APWXna (or compile and run it locally with javac
and java
rather than Eclipse)
Theory: From 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
, aNullPointerException
is raised, and the method reference expression completes abruptly.
(My emphasis.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With