Java. Function with possibly throwable params (NullpointerException)?

前端 未结 1 1186
情话喂你
情话喂你 2021-01-27 05:16

When I have a number of expressions that can throw an exception, for example:

instanceObj.final_doc_type = instance.getFinalDocument().getValue().getType().getVa         


        
相关标签:
1条回答
  • 2021-01-27 05:56

    Use Optional.map:

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

    This sets final_doc_type to null if anything in the chain is null.

    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);
    
    0 讨论(0)
提交回复
热议问题