Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a method reference on a null-reference does not throw an exception

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
    }
}
like image 883
Michael Avatar asked Jun 07 '16 14:06

Michael


1 Answers

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, a NullPointerException is raised, and the method reference expression completes abruptly.

(My emphasis.)

like image 177
4 revs Avatar answered Oct 26 '22 18:10

4 revs