Java. Function with possibly throwable params (Nul

2020-05-06 09:16发布

问题:

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

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 

So that I don't need to surround each expression with try-catch block or check every point for null.

回答1:

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