本文主要介绍Java中一个对象实例连续链式的调用多个方法,也就是通过一个方法获取一个对象,然后在调用该对象的方法,这样调用方法时更好的判断方法。

1、一般通常的判断方法

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;
}

2、 使用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);
}

3、使用||(或)运算符判断

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;
}

4、使用try-catch块判断

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