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. python小白 關于類里面的方法獲取變量失敗的問題2. thinkPHP5中獲取數據庫數據后默認選中下拉框的值,傳遞到后臺消失不見。有圖有代碼,希望有人幫忙3. linux運維 - python遠程控制windows如何實現4. Python2中code.co_kwonlyargcount的等效寫法5. javascript - 如何用最快的速度C#或Python開發一個桌面應用程序來訪問我的網站?6. django - Python error: [Errno 99] Cannot assign requested address7. mysql數據庫做關聯一般用id還是用戶名8. [python2]local variable referenced before assignment問題9. 求救一下,用新版的phpstudy,數據庫過段時間會消失是什么情況?10. python小白,關于函數問題
