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
    }
}
7
  • 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 stackoverflow.com/questions/37413106/…. Because it should throw an NPE at Runnable fn = test::m. Commented Jun 7, 2016 at 14:12
  • 4
    @Michael Yes, it seems there is a bug in Eclipse regarding this (same as the linked question). Commented Jun 7, 2016 at 14:23
  • 3
    Problem still exists in Eclipse Neon Commented Jun 7, 2016 at 14:29
  • 2
    Wow it's painful when your tools mislead you like that. Commented Jun 7, 2016 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 Commented Jun 7, 2016 at 14:38

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

3 Comments

Was this bug reported to Eclipse?
@DidierL: I've no idea, I don't use Eclipse.
As a workaround: Lambda, or static method reference does not throw in the evaluation phase, if you want to use nullable object's method anyway. [Runnable fn = () -> test.m()] or [Consumer<Test > c2 = Test ::m]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.