nullPointerException除非e.getKey()返回,否則下面的代碼會(huì)得到嗎nullMap<Integer, Optional<SecurityAttributeChange>> spnCreationDetails;Optional.ofNullable(spnCreationDetails.get(e.getKey()).orElse(new SecurityAttributeChange()).getNewAttribute()) .orElse(new SecurityAttr()) .getUserName());我在這一行中遇到了 NPE,是否可以調(diào)試它?我知道spnCreationDetails.get(e.getKey())返回 null,我null在這里處理時(shí)遺漏了什么嗎?- 編輯這是幾乎完整的方法,它將有助于提供有關(guān)如何重構(gòu)它以使其可讀的輸入。private void updateAuditFields(List<SecurityAttributeChange> securityChanges, Map<Integer, Map<String, Object>> result) { Map<Integer, Optional<SecurityAttributeChange>> spnModificationDetails = ... Map<Integer, Optional<SecurityAttributeChange>> spnCreationDetails = ... result.entrySet().stream().forEach(e -> { e.getValue() .put("userIdLastChanged", Optional.ofNullable(Optional.ofNullable(spnModificationDetails.get(e.getKey())) .orElse(Optional.of(new SecurityAttributeChange())) .get() .getNewAttribute()).orElse(new SecurityAttr()).getUserName()); e.getValue() .put("lastChangedDatetime", Optional.ofNullable(Optional.ofNullable(spnModificationDetails.get(e.getKey())) .orElse(Optional.of(new SecurityAttributeChange())) .get() .getNewAttribute()).orElse(new SecurityAttr()).getKnowledgeBeginDate()); e.getValue() .put("userIdCreated", Optional.ofNullable( Optional.ofNullable(spnCreationDetails.get(e.getKey())).orElse(Optional.of(new SecurityAttributeChange())).get().getNewAttribute()) .orElse(new SecurityAttr()) .getUserName()); });}
1 回答

泛舟湖上清波郎朗
TA貢獻(xiàn)1818條經(jīng)驗(yàn) 獲得超3個(gè)贊
如果spnCreationDetails.get(e.getKey())
可以為空,您可能需要:
Optional.ofNullable(spnCreationDetails.get(e.getKey())) .orElse(new SecurityAttributeChange()) .getNewAttribute() .orElse(new SecurityAttr()) .getUserName();
iespnCreationDetails.get(e.getKey())
應(yīng)該用Optional
.
編輯:看到您的評(píng)論,spnCreationDetails.get(e.getKey())
可以返回 anull
或 an Optional<SecurityAttributeChange>
,因此最好只將 thenull
轉(zhuǎn)換為 new Optional
:
spnCreationDetails.getOrDefault(e.getKey(),Optional.empty()) .orElse(new SecurityAttributeChange()) .getNewAttribute() .orElse(new SecurityAttr()) .getUserName();
添加回答
舉報(bào)
0/150
提交
取消