Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 474
ycomp Avatar asked Feb 09 '17 01:02

ycomp


1 Answers

Intellij-Jetbrains is very clever IDE and itself suggests you way for solving many problems.

Look at screenshot below. It suggests your five ways for removing this warning:

1) add assert value != null;

2) replace return statement with return value != null ? value.toString() : null;

3) surround with

    if (value != null) {
        return value.toString();
    }

4) suppress inspection for this particular statement by adding commentary:

//noinspection ConstantConditions
return value.toString();

5) add at least, as earlier @ochi suggested use @SuppressWarnings("ConstantConditions") annotation which can be used for method or for whole class.

To invoke this context menu use shortcut keys Alt+Enter (I think they are common for all OS).

enter image description here

like image 65
Andremoniy Avatar answered Oct 12 '22 23:10

Andremoniy