所以我有一个无法解决的SonarQube问题。
if (result instanceof AsyncResult) {
// Make sure handle async has been called
context.handleAsync();
Result newResult = context.controllerReturned();
if (newResult != null) {
result = newResult;
}
}
SonarQube声称context
可能在这里null
。如果您知道这是不正确的,则可以将此警告作为误报禁止显示。否则,您应该显式检查context
是否未null
:
if (result instanceof AsyncResult && context != null) {
// Here -------------------------^
// Make sure handle async has been called
context.handleAsync();
Result newResult = context.controllerReturned();
if (newResult != null) {
result = newResult;
}
}
试试这个:
if (result instanceof AsyncResult) {
if (context == null) {
//appropriate error handling
} else {
// Make sure handle async has been called
context.handleAsync();
Result newResult = context.controllerReturned();
if (newResult != null) {
result = newResult;
}
}
}
或者,您可以确保在初始化context
时,它永远不会获得值null
。如果 JSR303 是方法参数,您还可以查看 JSR303 @NotNull
context
注释。
你的问题可能在这里:
context.handleAsync();
Sonar所说的是(给定上下文[...]),在您的代码中的某个地方,您对context
进行了null
检查,但不是在这一部分中:
if (null == context) {
// bla bla bla
}
...
context.handleAsync(); // yes, but context was tested for null, so it can be null.
要么在使用时重新检查上下文,要么删除null
检查,要么在方法开始时失败:
if (null == context) {
throw new IllegalStateException("context is null");
}
或更好:
void yourMethod(Context context) {
Objects.requireNonNull(context, "context");
...
}
requireNonNull
方法作为前提条件调用;它的唯一目的是检查空值并提供(如果不省略)默认消息。