有没有更好的方法在Java中进行空检查? [重复]

问题描述 投票:23回答:4

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

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

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()完成。为了便于阅读,我在这里添加了多个ifs。

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

java if-statement conditional
4个回答
38
投票

你可以用这种方式使用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


15
投票

如果任何一个为null,则以下将返回true。如果所有值都不为null,则返回!source

private boolean sourceWebsite(Registration registration) {
      return registration.getApplication() == null 
      ||     registration.getApplication().getMetadata() == null
      ||     registration.getApplication().getMetadata().getSource() == null
      ||    !registration.getApplication().getMetadata().getSource();

}

更新 :

如果您希望每个getter都不会被调用多次,那么您可以为每个对象声明变量

private boolean sourceWebsite(Registration registration) {
      Application application;
      Metadata metadata;
      Boolean source;
      return (application = registration.getApplication()) == null 
      ||     (metadata = application.getMetadata()) == null
      ||     (source = metadata.getSource()) == null
      ||    !source;

 }

2
投票

您可以使用的另一个选项是try-catch块。如果得到空指针异常,则返回true。

private boolean sourceWebsite(Registration registration) {
    try {
        return !registration.getApplication().getMetadata().getSource();
    }
    catch (NullPointerException e) {
        return true;
    }
}

-2
投票

你可以使用像这样的hacky方法来做到这一点:

public static Object get(Object o, String... m) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
    if (o == null || m.length == 0) {
        return null;
    }
    for (String m1 : m) {
        o = o.getClass().getMethod(m1).invoke(o);
        if (o == null) {
            return null;
        }
    }
    return o;
}

并称之为:

Boolean source = (Boolean) get(registration, "getApplication", "getMetadata", "getSource");
return source == null ? false : !source;

但我不会在任何严肃的项目中这样做。

© www.soinside.com 2019 - 2024. All rights reserved.