当我有多个可以抛出异常的表达式时,例如:
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)?
发布评论