IntelliJ 空检查警告
IntelliJ null check warnings
我经常有这样的代码:
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 知道它进行了空值检查?并且不会显示警告?
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")
注释,它可用于方法或整个 class.
要调用此上下文菜单,请使用快捷键 Alt+Enter
(我认为它们对所有 OS 都是通用的)。
我经常有这样的代码:
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 知道它进行了空值检查?并且不会显示警告?
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")
注释,它可用于方法或整个 class.
要调用此上下文菜单,请使用快捷键 Alt+Enter
(我认为它们对所有 OS 都是通用的)。