[英]A "NullPointerException" could be thrown; "context" is nullable here
So I have an issue with SonarQube that I can not solve.所以我有一个无法解决的 SonarQube 问题。
if (result instanceof AsyncResult) {
// Make sure handle async has been called
context.handleAsync();
Result newResult = context.controllerReturned();
if (newResult != null) {
result = newResult;
}
}
SonarQube claims that context
may be null
here. SonarQube 声称
context
在这里可能为null
。 If you know this is incorrect, you could just suppress this warning as a false positive.如果您知道这是不正确的,您可以将此警告视为误报。 Otherwise, you should explicitly check if
context
is not 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;
}
}
Your problem is probably here:你的问题可能在这里:
context.handleAsync();
What Sonar says is (given the context [...]) that somewhere in your code, your doing a null
check on context
but not in this part: Sonar 所说的是(给定上下文 [...])在您的代码中的某处,您对
context
进行了null
检查,但不在此部分:
if (null == context) {
// bla bla bla
}
...
context.handleAsync(); // yes, but context was tested for null, so it can be null.
Either recheck the context when using it, either remove the null
check or fail at the beginning of your method:使用时重新检查上下文,删除
null
检查或在方法开始时失败:
if (null == context) {
throw new IllegalStateException("context is null");
}
Or better:或更好:
void yourMethod(Context context) {
Objects.requireNonNull(context, "context");
...
}
The requireNonNull
method is called as a precondition; requireNonNull
方法作为前提条件被调用; its only purpose is to check for nulls and provide (if you don't omit) a default message.它的唯一目的是检查空值并提供(如果您不省略)默认消息。
Try this:尝试这个:
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;
}
}
}
Alternatively you could ensure that when context
is initialised it can never get value null
.或者,您可以确保在初始化
context
时,它永远不会获得null
。 You could also look into the @NotNull
annotation from JSR303 if context
is a method parameter.如果
context
是方法参数,您还可以查看 JSR303 中的@NotNull
注释。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.