Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
902 views
in Technique[技术] by (71.8m points)

java - 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
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...