爪哇.具有可抛出参数的函数 (NullpointerException)?

编程入门 行业动态 更新时间:2024-10-09 22:17:17
本文介绍了爪哇.具有可抛出参数的函数 (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(); ...

是否有任何方法可以通过某些 one 函数 来处理这些表达式,如果参数无效并抛出异常,该函数将返回一些默认值(或 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 块包围每个表达式或检查每个点是否为空.

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

如果链中的任何内容为 null,这会将 final_doc_type 设置为 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);

更多推荐

爪哇.具有可抛出参数的函数 (NullpointerException)?

本文发布于:2023-11-28 17:02:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1643237.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:爪哇   抛出   函数   参数   NullpointerException

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!