IntelliJ null error warnings

I often have this code:

protected @Nullable Value value; public boolean hasValue() { return value != null; } 

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

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

then IntelliJ will warn me about a possible NPE

then

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

avoids this warning.

Is there a way to decorate my hasValue() method so that IntelliJ knows that it is doing a null check? and warning will not be displayed?

+5
source share
1 answer

Intellij-Jetbrains is a very smart development environment and itself offers you a way to solve many problems.

Take a look at the screenshot below. He offers five ways to resolve this warning:

1) add assert value != null ;

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

3) surround with

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

4) suppress the check for this particular statement by adding a comment:

 //noinspection ConstantConditions return value.toString(); 

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

To call this context menu, use the keyboard shortcuts Alt+Enter (I think that they are common to all OSs).

enter image description here

+1
source

Source: https://habr.com/ru/post/1263996/


All Articles