简体   繁体   中英

Java. Function with possibly throwable params (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();
...

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM