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?
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:
- Copy
myVar
into a local variable; - Use
localMyVar != null
andlocalMyVar.bar()
.