yco*_*omp 6 java annotations jetbrains-ide intellij-idea
我经常有这样的代码:
protected @Nullable Value value;
public boolean hasValue() { return value != null; }
Run Code Online (Sandbox Code Playgroud)
这个问题是,当我做这样的空检查时:
if (!hasValue()) throw...
return value.toString();
Run Code Online (Sandbox Code Playgroud)
然后IntelliJ会警告我可能的NPE
而
if (value != null) throw...
return value.toString();
Run Code Online (Sandbox Code Playgroud)
避免这个警告.
有没有办法装饰我的hasValue()方法,以便IntelliJ知道它进行空检查?并且不会显示警告?
Intellij-Jetbrains 是非常聪明的 IDE,它本身就为您提供了解决许多问题的方法。
看下面的截图。它建议您消除此警告的五种方法:
1)添加assert value != null;
2) 将 return 语句替换为return value != null ? value.toString() : null;
3) 围绕
if (value != null) {
return value.toString();
}
Run Code Online (Sandbox Code Playgroud)
4) 通过添加注释来抑制对此特定语句的检查:
//noinspection ConstantConditions
return value.toString();
Run Code Online (Sandbox Code Playgroud)
5)至少添加,正如之前 @ochi 建议使用@SuppressWarnings("ConstantConditions")可用于方法或整个类的注释。
要调用此上下文菜单,请使用快捷键Alt+Enter(我认为它们对于所有操作系统都是通用的)。
| 归档时间: |
|
| 查看次数: |
1508 次 |
| 最近记录: |