Nested objects null checking

前端 未结 1 1756
北荒
北荒 2021-01-15 01:50

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

相关标签:
1条回答
  • 2021-01-15 02:36

    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()));
    
    0 讨论(0)
提交回复
热议问题