Java。具有可能拋出參數(shù)的函數(shù)(NullpointerException)?
用途Optional.map:
instanceObj.final_doc_type = Optional.ofNullable(instance) .map(Instance::getFinalDocument) .map(Document::getValue) .map(Value::getType) .map(Type::getValue) .orElse(null);
這設(shè)置final_doc_type為null鏈中是否有任何東西null。
如果只想在非空值的情況下設(shè)置其值,請刪除分配,并將其更改orElse為ifPresent:
Optional.ofNullable(instance) /* ... */ .ifPresent(t -> instanceObj.final_doc_type = t);解決方法
當(dāng)我有許多可以引發(fā)異常的表達(dá)式時(shí),例如:
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();...
有沒有處理這些表達(dá)式通過某種方法 一個(gè) 功能 ,將返回一些默認(rèn)值(或空)如果一個(gè)參數(shù)是無效的,并拋出一個(gè)異常-這可能發(fā)生,如果,例如:
instance.getFinalDocument().getValue().getDate() = null
這樣我就不需要用try-catch塊包圍每個(gè)表達(dá)式或檢查每個(gè)點(diǎn)是否為null。
相關(guān)文章:
1. docker綁定了nginx端口 外部訪問不到2. 前端 - html5 audio不能播放3. javascript - 最近用echarts做統(tǒng)計(jì)圖時(shí)遇到兩個(gè)問題!!4. javascript - 深夜被問題困擾求解惑,rn的API之PermissionsAndroidd的問題5. mysql - 我的myeclipse一直連顯示數(shù)據(jù)庫連接失敗,不知道為什么6. redis sentinel怎么跑守護(hù)進(jìn)程以及日志記錄位置的?7. android權(quán)限被第三方安全軟件禁止,如何獲取該權(quán)限狀態(tài)8. android - 優(yōu)酷的安卓及蘋果app還在使用flash技術(shù)嗎?9. 利用百度地圖API定位及附件商家信息服務(wù)10. nginx - ssl加密訪問證書不受信任

網(wǎng)公網(wǎng)安備