Java方法参考引发NPE [英] Java method reference throws NPE

查看:86
本文介绍了Java方法参考引发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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆