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

标签 java exception nullpointerexception

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

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/

相关文章:

java - 使用cordova发送消息到webview进行处理

java - 在 Intellij Ultimate 上找不到新 Web 应用程序的选项

c++ - SIGABRT 试图抛出异常时

c# - 当我通过安装程序运行应用程序时,出现错误 "Bad method token. "

java - 什么情况下会抛出IllegalStateException?

android - 如何保存应用程序类状态

java - EDT 违规是否可能导致外部软件出现 NullPointerException?

java - 如何为“列表”首选项中的选项设置 onClick 监听器?

java - spring mvc文件上传在gradle中不起作用

android - 应用程序因空指针异常而崩溃