Java的。可能抛出的params(NullpointerException)的函数? [英] Java. Function with possibly throwable params (NullpointerException)?
问题描述
当我有许多可以抛出异常的表达式时,例如:
When I have a number of expressions that can throw an exception, for example:
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();
...
是否有任何方法可以通过某些来处理这些表达式 函数,如果参数无效并引发异常,将返回一些默认值(或null) - 例如:
is there any method to handle these expressions by some one function that will return some default value (or null) IF a parameter is invalid and throws an exception - this can take place if, for example:
instance.getFinalDocument().getValue().getDate() = null
这样我就不需要用try-catch块包围每个表达式,也不需要检查每个点是否为null。
So that I don't need to surround each expression with try-catch block or check every point for null.
推荐答案
使用 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
。
This sets final_doc_type
to null
if anything in the chain is null
.
如果您只想在非空值的情况下设置其值,请删除该分配,并更改 orElse
到 ifPresent
:
If you only want to set its value in the case of a non-null value, remove the assignment, and change the orElse
to ifPresent
:
Optional.ofNullable(instance)
/* ... */
.ifPresent(t -> instanceObj.final_doc_type = t);
这篇关于Java的。可能抛出的params(NullpointerException)的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!