gpt4 book ai didi

java 。具有可能可抛出参数的函数(NullpointerException)?

转载 作者:行者123 更新时间:2023-12-01 07:18:25 25 4
gpt4 key购买 nike

当我有多个可能引发异常的表达式时,例如:

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) - 这可以发生,例如:

instance.getFinalDocument().getValue().getDate() = null 

这样我就不需要用 try-catch block 包围每个表达式或检查每个点是否为 null。

最佳答案

使用Optional.map :

instanceObj.final_doc_type = 
Optional.ofNullable(instance)
.map(Instance::getFinalDocument)
.map(Document::getValue)
.map(Value::getType)
.map(Type::getValue)
.orElse(null);

如果链中的任何内容为 null,则这会将 final_doc_type 设置为 null

如果您只想在非空值的情况下设置其值,请删除该赋值,并将 orElse 更改为 ifPresent:

Optional.ofNullable(instance)
/* ... */
.ifPresent(t -> instanceObj.final_doc_type = t);

关于 java 。具有可能可抛出参数的函数(NullpointerException)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49272971/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com