这个问题在这里已经有了答案:
Check chains of "get" calls for null
(10 个回答)
去年关闭。
我需要使用对象中 3 个级别的 getter。
response.getServiceError().getErrorCode()
一个或多个对象可能为 NULL。现在,我正在这样做if (response != null && response.getServiceError() != null && response.getServiceError().getErrorCode() != null && response.getServiceError().getErrorCode().equals("errCode123")) {
//doSomething;
}
有没有更好和/或优雅的方式来构建 if 条件?
最佳答案
使用 Optional
!
Optional.ofNullable(response)
.map(Response::getServiceError)
.map(ServiceError::getErrorCode)
.filter(code -> code.equals("errCode123"))
.ifPresent(code -> {
// doSomething
});
关于java - Java 11 中的高效空检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63946331/