Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java method reference throws NPE

So I got a class

public class MenuBar extends JMenuBar {

    MenuBarController controller;

    public MenuBar() {
        JMenu menu = new JMenu("File");
        menu.add(createMenuItem("Report", controller::writeReport));
        menu.add(createMenuItem("Save", controller::save));
        menu.add(createMenuItem("Import", controller::importFile));
        menu.add(createMenuItem("Clear DB", controller::clearDatabase));
        add(menu);
    }

    public void setController(MenuBarController controller) {
        this.controller = controller;
    }
}

MenuBarController is an interface whose implementation is set via setController after the MenuBar ist created. The code throws a NullpointerException at menu.add(createMenuItem("Report", controller::writeReport)) which can only be caused by controller::writeReport. If I replace this with a lambda like () -> controller.writeReport() no NPE is thrown.

1. Why does controller::writeReport throw an NPE?

2. Why doesn't the lambda throw an NPE?

The funny part is: If I replace the lambda with the method reference used before after I ran it once with the lambda, no more NPEs are thrown.

Anyone got any idea why that could be? Some javac / eclipse weirdness?

like image 630
jheyd Avatar asked Nov 05 '15 20:11

jheyd


People also ask

Can we handle NullPointerException in Java?

In Java, the java. lang. NullPointerException is thrown when a reference variable is accessed (or de-referenced) and is not pointing to any object. This error can be resolved by using a try-catch block or an if-else condition to check if a reference variable is null before dereferencing it.

Can we catch NullPointerException?

It is generally a bad practice to catch NullPointerException. Programmers typically catch NullPointerException under three circumstances: The program contains a null pointer dereference. Catching the resulting exception was easier than fixing the underlying problem.

Can NPE be extended Java?

Java NullPointerException (NPE) is an unchecked exception and extends RuntimeException .


1 Answers

controller::writeReport throws an NPE because controller is null when the line is evaluated.

() -> controller.writeReport() does not throw an NPE because by the time the lambda is run, controller has been given a value.

like image 127
Ian McLaird Avatar answered Nov 02 '22 10:11

Ian McLaird