java - JAVA 8 中的 NULL 安全对象检查

标签 java if-statement java-8 null option-type

所以我想对包含在值中的值进行空安全检查。

所以我有 3 个对象:

Person has a clothes object which has a country object which has a capital

所以一个人可能没有衣服,所以这样的检查会抛出一个空指针:

if (person.getClothes.getCountry.getCapital)

如果路径上的任何对象为 null,我如何使这样的语句只返回 false?

我也不想这样做。 (如果可能,使用 Java-8 中的单行代码。

if (person !=null) {
    if (person.getClothes != null) {
        if (person.getClothes.getCountry !=null) {
            etc....
        }
    }
}

最佳答案

您可以通过 Optional::map 链接所有这些调用。我觉得这比 if/else 更容易阅读,但可能只有我会这样

Optional.ofNullable(person.getClothes())
        .map(Clothes::getCountry)
        .map(Country::getCapital)
        .ifPresent(...)

关于java - JAVA 8 中的 NULL 安全对象检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52220606/

相关文章:

java - 将微秒时间转换为毫秒时间

java - 无法在 Eclipse 上编写 Java 8 代码?

html - Django : Could not parse the remainder: '{{' from '{{

mysql - 具有未知值的 SQL if 语句

php - 如何使用 elesif 获取不同的错误消息

Java : use Streams to convert List<Object> to another List<anotherObject>

java - Android Studio 创建操作栏

java - 用于 Yubico OpenPGP 智能卡的 PGP 数据加密

java - ActiveMQ - 创建监听 SSL (TLS) 传输错误的嵌入式代理

java - ORA-24816 : Expanded non LONG bind data supplied after actual LONG or LOB column