我经常有这样的代码:
protected @Nullable Value value;
public boolean hasValue() { return value != null; }
这个问题是当我做这样的空检查时:
if (!hasValue()) throw...
return value.toString();
然后IntelliJ会警告我可能的NPE
,而
if (value != null) throw...
return value.toString();
避免此警告。
有没有办法装饰我的hasValue()
方法,以便IntelliJ知道它进行空检查?并且不会显示警告?
答案 0 :(得分:1)
Intellij-Jetbrains是一个非常聪明的IDE,它本身就是你解决许多问题的方法。
请看下面的截图。它建议您删除此警告的五种方法:
1)添加assert value != null
;
2)将return语句替换为return value != null ? value.toString() : null;
3)环绕
if (value != null) {
return value.toString();
}
4)通过添加评论来抑制对此特定陈述的检查:
//noinspection ConstantConditions
return value.toString();
5)至少添加,因为之前的@ochi建议使用@SuppressWarnings("ConstantConditions")
注释,可以用于方法或整个类。
要调用此上下文菜单,请使用快捷键Alt+Enter
(我认为它们适用于所有操作系统)。