IntelliJ null check warnings

僤鯓⒐⒋嵵緔 提交于 2019-12-07 01:54:11

问题


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?


回答1:


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).



来源:https://stackoverflow.com/questions/42126828/intellij-null-check-warnings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!