提问人:AylaWinters 提问时间:5/10/2023 更新时间:5/10/2023 访问量:256
SonarLint res.getBody() 即使在 null 检查后也可以为 null
SonarLint res.getBody() can be null even after a null check
问:
我似乎无法解决 Spring Boot 应用程序中的 SonarLint 问题。即使经过空检查,我仍然得到
A "NullPointerException" could be thrown; "getBody()" is nullable here.
其他问题提到将其分配给变量(因此是),但这也不起作用。Object resBody
public ResponseEntity<Object> doSomethingCool(String foo, String bar) {
ResponseEntity<Object> res;
try {
res = myService.doTheWork(foo, bar);
if (res.hasBody() && res.getBody() != null) {
Object resBody = res.getBody();
if (res.getStatusCode() == HttpStatus.OK) {
myLogger(resBody.toString(), res.getStatusCode());
}
}
} catch (Exception e) {
return customErrorHandling(res, e);
}
return res;
}
getBody() 如何在检查 null 的代码块中仍然是 null?如何在 SonarLint 中解决此问题?
答:
2赞
AylaWinters
5/10/2023
#1
正如 Joachim Sauer 所提到的,我在 null 检查后声明了变量。所以:
public ResponseEntity<Object> doSomethingCool(String foo, String bar) {
ResponseEntity<Object> res;
try {
res = myService.doTheWork(foo, bar);
Object resBody = res.getBody(); //<--------here
if (resBody != null) {
if (res.getStatusCode() == HttpStatus.OK) {
myLogger(resBody.toString(), res.getStatusCode());
}
}
} catch (Exception e) {
return customErrorHandling(res, e);
}
return res;
}
评论
res.getBody()
getBody()
Object resBody; if (res.hasBody() && (resBody = res.getBody()) != null) {