Search code examples
javaintellij-ideaannotationsjetbrains-ide

IntelliJ null check warnings


I often have code like this:

protected @Nullable Value value;

public boolean hasValue() { return value != null; }

the problem with this is that when I do null checks like so:

if (!hasValue()) throw...
return value.toString();

then IntelliJ will warn me about a possible NPE

whereas

if (value != null) throw...
return value.toString();

avoids this warning.

is there a way to decorate my hasValue() method so that IntelliJ knows it does a null check? and won't display the warning?


Solution

  • The actual correct answer is to add a @Contract annotation to the method checking for null.

    See: https://blog.jetbrains.com/idea/2013/10/better-control-flow-analysis-with-contract-annotations-and-intellij-idea-13/

    Credits: How can I make IntelliJ IDEA understand my null-checking method?