提问人:Bunyamin 提问时间:8/23/2022 更新时间:8/25/2022 访问量:23
如何处理 nullPointerException
how to handle nullPointerException
问:
public List<PostResponse> getAllPosts(Optional<Long> userId) {
List<Post> list;
if (userId.isPresent())
list = postRepository.findByUserId(userId.get());
list = postRepository.findAll();
return list.stream().map(p -> {
List<LikeResponse> likes = likeService.getAllLikesWithParam(Optional.ofNullable(null), Optional.of(p.getId()));
return new PostResponse(p, likes);}).collect(Collectors.toList());
}
public List<LikeResponse> getAllLikesWithParam(Optional<Long> userId, Optional<Long> postId) {
List<Like> list;
if(userId.isPresent() && postId.isPresent()) {
list = likeRepository.findByUserIdAndPostId(userId.get(), postId.get());
}else if(userId.isPresent()) {
list = likeRepository.findByUserId(userId.get());
}else if(postId.isPresent()) {
list = likeRepository.findByPostId(postId.get());
}else
list = likeRepository.findAll();
return list.stream().map(like -> new LikeResponse(like)).collect(Collectors.toList());
}
我在这一行的 getAllPosts 中出错 Optional.ofNullable(null) 错误是:java.lang.NullPointerException:null
答:
0赞
L. Schilling
8/25/2022
#1
我无法仅从粘贴的代码中看出,但似乎 likeService 很可能是 null。
此外,我建议使用 Optional.empty() 而不是 Optional.ofNullable(null),但这似乎不是这里问题的原因。
评论