Java。具有可能拋出參數的函數(NullpointerException)?
用途Optional.map:
instanceObj.final_doc_type = Optional.ofNullable(instance) .map(Instance::getFinalDocument) .map(Document::getValue) .map(Value::getType) .map(Type::getValue) .orElse(null);
這設置final_doc_type為null鏈中是否有任何東西null。
如果只想在非空值的情況下設置其值,請刪除分配,并將其更改orElse為ifPresent:
Optional.ofNullable(instance) /* ... */ .ifPresent(t -> instanceObj.final_doc_type = t);解決方法
當我有許多可以引發異常的表達式時,例如:
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();...
有沒有處理這些表達式通過某種方法 一個 功能 ,將返回一些默認值(或空)如果一個參數是無效的,并拋出一個異常-這可能發生,如果,例如:
instance.getFinalDocument().getValue().getDate() = null
這樣我就不需要用try-catch塊包圍每個表達式或檢查每個點是否為null。
相關文章:
1. html5和Flash對抗是什么情況?2. html5 - datatables 加載不出來數據。3. docker 下面創建的IMAGE 他們的 ID 一樣?這個是怎么回事????4. 利用IPMI遠程安裝centos報錯!5. node.js - mongodb查找子對象的名稱為某個值的對象的方法6. 運行python程序時出現“應用程序發生異常”的內存錯誤?7. 測試自動化html元素選擇器元素ID或DataAttribute [關閉]8. javascript - QQ第三方登錄的問題9. javascript - 在 model里定義的 引用表模型時,model為undefined。10. spring-mvc - spring-session-redis HttpSessionListener失效

網公網安備