爪哇.具有可抛出参数的函数 (NullpointerException)? [英] Java. Function with possibly throwable params (NullpointerException)?

查看: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)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆