Nullable variable is checked for null in method but not recognized

moonlight :

I am using IntelliJ IDEA's code inspection to evaluate the @Nullable annotations. At the moment I am using the org.jetbrains.annotations package, however I could also switch to another implementation if that helps with the problem.

The problem is that the nullity check of an annotated variable is done in another method. This is not recognized by the code inspector.

@Nullable
private Bar myVar;

public boolean isNotNull() {
    // This check is actually more complex, but will
    // only ever return true if myVar is not null
    return myVar != null;
}

public void foo() {
    if (isNotNull()) {
        // Here I get a warning that myVar might be null
        myVar.bar();
    }
}

Can I somehow make IntelliJ recognize this condition?

Andy Turner :

I suspect that intellij is complaining because it doesn't know that the return value of isNotNull() indicates the nullity of myVar.

However, it could be null at that point you invoke bar().

Some other thread could sneak in and change myVar back to null in between invoking isNotNull() and using myVar.

The only way to guarantee it is to:

  1. Copy myVar into a local variable;
  2. Use localMyVar != null and localMyVar.bar().

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=142668&siteId=1