I know many ways how to check on nested objects for a NullPointerException
, as for Java 8 the simplest is to apply the Optional
.
or t
As you mentioned yourself in the question, use Optional
, but it's more lenghty.
excel.setCell(name1, Optional.of(contract).map(Contract::getContactInfo).map(ContactInfo::getPosition).orElse(null));
excel.setCell(name2, Optional.of(contract).map(Contract::getEntitledPerson).map(Person::getEmail).orElse(null));
Which is more easily read when formatted like this:
excel.setCell(name1, Optional.of(contract)
.map(Contract::getContactInfo)
.map(ContactInfo::getPosition)
.orElse(null));
excel.setCell(name2, Optional.of(contract)
.map(Contract::getEntitledPerson)
.map(Person::getEmail)
.orElse(null));
If your goal is smallest code, you could just catch the NullPointerException
. It's a bit of a hack, in my opinion, but it'll do the trick.
First, a helper method:
public static <T> T nullGuard(Supplier<T> supplier) {
try {
return supplier.get();
} catch (@SuppressWarnings("unused") NullPointerException ignored) {
return null;
}
}
Then you wrapper the expression in question:
excel.setCell(name1, nullGuard(() -> contract.getContactInfo().getPosition()));
excel.setCell(name2, nullGuard(() -> contract.getEntitledPerson().getEmail()));