11

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
    }
}
Michael
  • 4,722
  • 6
  • 37
  • 58
  • 5
    Are you testing with Eclipse? I tested with JDK 1.8.0_51 and it throws the NPE where expected. This probably answers the question then http://stackoverflow.com/questions/37413106/thread-setuncaughtexceptionhandler-and-java-8-method-reference/. Because it should throw an NPE at `Runnable fn = test::m`. – Tunaki Jun 07 '16 at 14:12
  • I'm voting to close this question as off-topic because it's asking about behavior that doesn't exist. – T.J. Crowder Jun 07 '16 at 14:16
  • @Tunaki yes I tested in Eclipse and it does not throw an exception when I uncomment the last line – Michael Jun 07 '16 at 14:22
  • 4
    @Michael Yes, it seems there is a bug in Eclipse regarding this (same as the linked question). – Tunaki Jun 07 '16 at 14:23
  • 3
    Problem still exists in Eclipse Neon – Jorn Vernee Jun 07 '16 at 14:29
  • 2
    *Wow* it's painful when your tools mislead you like that. – T.J. Crowder Jun 07 '16 at 14:36
  • 1
    It makes a kind of sense, since for this type of method reference, the left side of the :: is an expression that returns a reference. While this is more explicitly a null reference, this would have the same effect: `functionThatReturnsNull()::method` – Hank D Jun 07 '16 at 14:38

1 Answers1

12

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.)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875