Java 11中的有效null检查

问题描述

我需要使用在对象内3级以下的吸气剂。

response.getServiceError().getErrorCode()

一个或多个对象可能为NULL。现在,我正在这样做

if (response != null && response.getServiceError() != null && response.getServiceError().getErrorCode() != null && response.getServiceError().getErrorCode().equals("errCode123")) {
     //doSomething;
}

是否存在一种更好和/或更优雅的方式来构造条件?

解决方法

使用Optional

Optional.ofNullable(response)
    .map(Response::getServiceError)
    .map(ServiceError::getErrorCode)
    .filter(code -> code.equals("errCode123"))
    .ifPresent(code -> {
        // doSomething
    });

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...