可能会抛出“ NullPointerException”。 “上下文”在此处为空

时间:2018-12-22 11:22:52

标签: java asynchronous sonarqube static-analysis

所以SonarQube有一个我无法解决的问题。

if (result instanceof AsyncResult) {
    // Make sure handle async has been called
    context.handleAsync();
    Result newResult = context.controllerReturned();
    if (newResult != null) {
        result = newResult;
    }
 }

3 个答案:

答案 0 :(得分:1)

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;
    }
}

答案 1 :(得分:0)

您的问题可能在这里:

if MaxAge>Oldest:
    Oldest = MaxAge

Sonar说的是(鉴于上下文[...]),即您在代码中的某处对context.handleAsync(); 进行了null检查,但在本部分中却没有:

context

在使用上下文时要么重新检查上下文,要么删除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"); ... } 方法被称为前提条件;它的唯一目的是检查null并提供(如果您不忽略)默认消息。

答案 2 :(得分:0)

尝试一下:

requireNonNull

或者,您可以确保初始化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的@NotNull注释。