Java方法参考引发NPE [英] Java method reference throws NPE
问题描述
所以我上了课
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
是在创建MenuBar ist之后通过setController
设置其实现的接口.该代码在menu.add(createMenuItem("Report", controller::writeReport))
处引发NullpointerException,该异常只能由controller::writeReport
引起.如果我将其替换为() -> controller.writeReport()
这样的lambda,则不会引发NPE.
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.为什么controller::writeReport
抛出NPE?
1. Why does controller::writeReport
throw an NPE?
2.为什么lambda不抛出NPE?
有趣的部分是:如果在用lambda运行一次之后,我用之前使用的方法引用替换了lambda,则不会再抛出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.
任何人都知道为什么会这样吗?一些javac/eclipse怪异吗?
Anyone got any idea why that could be? Some javac / eclipse weirdness?
推荐答案
controller::writeReport
引发NPE,因为在评估该行时controller
为空.
controller::writeReport
throws an NPE because controller
is null when the line is evaluated.
() -> controller.writeReport()
不会引发NPE,因为在运行lambda时,已经为controller
赋予了一个值.
() -> controller.writeReport()
does not throw an NPE because by the time the lambda is run, controller
has been given a value.
这篇关于Java方法参考引发NPE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!