在嵌套 class 上调用 getter 方法时如何避免 NullPointerExceptions

How to avoid NullPointerExceptions when calling getter-methods on a nested class

希望你能帮我解决我的问题。实际上我知道有解决方案(例如 nullchecking),但我正在寻找一个超级优雅的解决方案!在最好的情况下,一个班轮。希望你能帮助我。

现在我将通过简单的例子来描述问题。

情况描述

我有一个 Java 对象,它在其他简单成员变量旁边包含其他 Java 对象(嵌套 Java 对象)。

Class 店铺:

Class 员工:

...等等。

可以看到 Store 对象 -> 包含:Employee 对象 -> 包含:BankAccount 对象。

问题

要从 Store 对象调用 Employee 的年龄,我会做:

Store.getEmployee().getAge();

或者如果我想要银行账户 IBAN,我将不得不这样做

Store.getEmployee().getBankAccount().getIban();

但是,如果一家商店 没有 名员工,.getEmployee() 将导致 NullPointerException。 银行账户也是如此。

当然可以

if(Store.getEmployee() != null) {
    if(Store.getEmployee().getBankAccount() != null) {
        System.out.println(Store.getEmployee().getBankAccount().getIban();
    }
}

但这太烦人了。

有更简单的解决方法吗?

注意:可选项也不起作用,因为

Optional.ofNullable(Store.getEmployee().getBankAccount().getIban().orElse("");

不起作用,当 Store.getEmployee() 已经引起异常时。

编辑 请注意,对象本身不应该是解决方案的一部分。当然,您可以修改对象,使 return 成为可选对象或自行进行空值检查。 这背后的原因是您只是获取对象并对其进行处理,但不允许您配置它们。

您可以使用以下内容:

Optional.ofNullable(store.getEmployee())
        .map(Employee::getBankAccount)
        .map(BankAccount::getIban)
        .orElse("")

您还应该考虑使用 return 类型 Optional<Employee> 定义 getEmployee 方法,在这种情况下您可以将其更改为:

store.getEmployee()
        .map(Employee::getBankAccount)
        .map(BankAccount::getIban)
        .orElse("")