栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

嵌套对象空检查

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

嵌套对象空检查

正如您在问题中提到自己时,请使用

Optional
,但是它比较宽松。

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

像这样格式化时更容易阅读:

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

如果您的目标是最小的代码,则只需捕获即可

NullPointerException
。在我看来,这有点骇人听闻,但是可以解决问题。

首先,一个辅助方法:

public static <T> T nullGuard(Supplier<T> supplier) {    try {        return supplier.get();    } catch (@SuppressWarnings("unused") NullPointerException ignored) {        return null;    }}

然后包装有问题的表达式:

excel.setCell(name1, nullGuard(() -> contract.getContactInfo().getPosition()));excel.setCell(name2, nullGuard(() -> contract.getEntitledPerson().getEmail()));


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/417092.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号