gpt4 book ai didi

java - 有没有更好的方法在 Java 中进行空检查?

转载 作者:IT老高 更新时间:2023-10-28 20:31:53 27 4
gpt4 key购买 nike

这可能看起来像一个原始问题,或者这可以通过我不知道的简单实用程序库方法来完成。

目标是检查嵌套在两个对象下的 boolean 字段的值。

private boolean sourceWebsite(Registration registration) {
Application application = registration.getApplication();
if (application == null) {
return true;
}

Metadata metadata = application.getMetadata();
if (metadata == null) {
return true;
}

Boolean source = metadata.getSource();
if (source == null) {
return true;
}

return !source;
}

我知道这可以在单个 if() 中完成。为了便于阅读,我在这里添加了多个 if

有没有一种方法可以简化上面的 if 语句,并有一个简单的实用程序类,如果父对象或不为 null,则返回 Boolean source 的值?

最佳答案

您可以使用 java.util.Optional这样:

private boolean sourceWebsite(Registration registration) {
return Optional.of(registration)
.map(Registration::getApplication)
.map(Application::getMetadata)
.map(Metadata::getSource)
.map(source -> !source)
.orElse(Boolean.TRUE);
}

简而言之,如果任何 getter 返回 null,这将返回 true,否则返回 !Metadata.source

关于java - 有没有更好的方法在 Java 中进行空检查?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55630570/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com