IntelliJ 空检查警告 [英] IntelliJ null check warnings
问题描述
我经常有这样的代码:
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();
然后 IntelliJ 会警告我可能的 NPE
then IntelliJ will warn me about a possible NPE
而
if (value != null) throw...
return value.toString();
避免此警告.
有没有办法装饰我的 hasValue()
方法,以便 IntelliJ 知道它执行空检查?并且不会显示警告?
is there a way to decorate my hasValue()
method so that IntelliJ knows it does a null check? and won't display the warning?
推荐答案
Intellij-Jetbrains 是非常聪明的 IDE,它本身会为您提供解决许多问题的方法.
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) 添加 assert value != null
;
2) 用 return value != null 替换 return 语句?value.toString() : null;
3) 用
if (value != null) {
return value.toString();
}
4) 通过添加注释来抑制对这个特定语句的检查:
4) suppress inspection for this particular statement by adding commentary:
//noinspection ConstantConditions
return value.toString();
5) 至少添加,正如之前@ochi 建议使用 @SuppressWarnings("ConstantConditions")
注释,该注释可用于方法或整个类.
5) add at least, as earlier @ochi suggested use @SuppressWarnings("ConstantConditions")
annotation which can be used for method or for whole class.
要调用此上下文菜单,请使用快捷键Alt+Enter
(我认为它们对于所有操作系统都是通用的).
To invoke this context menu use shortcut keys Alt+Enter
(I think they are common for all OS).
这篇关于IntelliJ 空检查警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!