當項目運行時拋出 NullPointerException 空指針異常的錯誤時,可以
考慮使用Optional來處理null的問題。
例子如下:
@Override
public ReplyStatusResponse replyStatusList(Long replyId) {
LOGGER.debug(CommonLogDomain.BUSINESS, "replyStatusList,replyId:{}", replyId);
ReplyStatusResponse replyStatusResponse = new ReplyStatusResponse();
PostReplyInfo r = postReplyInfoService.selectByPrimaryKey(replyId);
Integer r1 = Optional.ofNullable(r).map(PostReplyInfo::getSelfPrivate).map(t -> t.intValue()).orElse(0);
Integer r2 = Optional.ofNullable(r).map(PostReplyInfo::getPortalHidden).map(t -> t.intValue()).orElse(0);
Integer replyIdStatus = (r1 + r2 == 0) ? 0 : 1;
replyStatusResponse.setReplyIdStatus((replyIdStatus.byteValue()));
return replyStatusResponse;
}
基本語法:
Optional.ofNullable(r).map(PostReplyInfo::getSelfPrivate).map(t -> t.intValue()).orElse(0);