以下代码将永远获得nullPointerException
,除非e.getKey()
返回null
Map<Integer, Optional<SecurityAttributeChange>> spnCreationDetails;
Optional.ofNullable(spnCreationDetails.get(e.getKey()).orElse(new SecurityAttributeChange()).getNewAttribute())
.orElse(new SecurityAttr())
.getUserName());
我在这一行中正在使用NPE,是否可以调试它?我知道spnCreationDetails.get(e.getKey())
返回null,在这里处理null
时我错过了什么吗?
-编辑
这里是几乎完整的方法,它将帮助您提供有关如何重构它以便使其可读的输入。
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());
e.getValue()
.put("createdDatetime",
Optional.ofNullable(Optional.ofNullable(spnCreationDetails.get(e.getKey()))
.orElse(Optional.of(new SecurityAttributeChange()))
.get()
.getNewAttribute()).orElse(new SecurityAttr()).getKnowledgeBeginDate());
});
}
答案 0 :(得分:5)
如果spnCreationDetails.get(e.getKey())
为空,则可能需要:
Optional.ofNullable(spnCreationDetails.get(e.getKey()))
.orElse(new SecurityAttributeChange())
.getNewAttribute()
.orElse(new SecurityAttr())
.getUserName();
即spnCreationDetails.get(e.getKey())
应该用Optional
包装。
编辑:看到您的评论,spnCreationDetails.get(e.getKey())
可以返回null
或Optional<SecurityAttributeChange>
,因此最好将null
转换为新的{{ 1}}:
Optional