如何解决Java。具有可能抛出参数的函数(NullpointerException)??
用途Optional.map
:
instanceObj.final_doc_type =
Optional.ofNullable(instance)
.map(Instance::getFinalDocument)
.map(Document::getValue)
.map(Value::getType)
.map(Type::getValue)
.orElse(null);
这设置final_doc_type
为null
链中是否有任何东西null
。
如果只想在非空值的情况下设置其值,请删除分配,并将其更改orElse
为ifPresent
:
Optional.ofNullable(instance)
/* ... */
.ifPresent(t -> instanceObj.final_doc_type = t);
解决方法
当我有许多可以引发异常的表达式时,例如:
instanceObj.final_doc_type = instance.getFinalDocument().getValue().getType().getValue();
instanceObj.final_doc_date = instance.getFinalDocument().getValue().getDate().toGregorianCalendar().getTime();
instanceObj.appeal_date = instance.getFinalDocument().getValue().getAppealDate().getValue().toGregorianCalendar().getTime();
...
instanceObj.start_doc_type = instance.getStartDocument().getValue().getDocType().getValue();
instanceObj.apeealed_type = instance.getStartDocument().getValue().getApeealedType().getValue();
instanceObj.declarers_list_mult_id = instance.getStartDocument().getValue().getDeclarers().getValue().getString();
...
有没有处理这些表达式通过某种方法 一个 功能 ,将返回一些默认值(或空)如果一个参数是无效的,并抛出一个异常-这可能发生,如果,例如:
instance.getFinalDocument().getValue().getDate() = null
这样我就不需要用try-catch块包围每个表达式或检查每个点是否为null。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。