Reputation: 8583
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?
Upvotes: 11
Views: 5069
Reputation: 62
The actual correct answer is to add a @Contract
annotation to the method checking for null.
Credits: How can I make IntelliJ IDEA understand my null-checking method?
Upvotes: 2
Reputation: 34920
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).
Upvotes: 6