下面是一些可以抛出 NullPointerException 的代码片段。
01:
public void m1(@Nullable String text) {
System.out.print(text.toLowerCase()); // <-- expect to be reported.
}
02:
private boolean _closed = false;
public void m1(@Nullable String text) {
if(_closed)
return;
System.out.print(text.toLowerCase()); // <-- expect to be reported.
}
03:
public void m1(@NotNull String text) {
System.out.print(text.toLowerCase());
}
public @Nullable String getText() {
return "Some text";
}
public void m2() {
m1(getText()); // <-- expect to be reported.
}
不同的人可以使用不同的静态分析工具。最好能收集信息,哪些工具能够检测和报告问题,哪些失败了。另外,如果您有自己的场景,请发布它们。
这是我的结果
FindBugs (1.3.9):
- 01: [S] 参数必须为非空但标记为可为空
- 02: [F] 未报告
- 03: [F] 未报告
IntelliJ IDE 9.0.2(社区版):
- 01: [S] 方法调用 text.toLowerCase() 可能产生 java.lang.NullPointerException
- 02: [S] 方法调用 text.toLowerCase() 可能产生 java.lang.NullPointerException
- 03: [S] 参数 getText() 可能为空
- 01:[S] 取消引用可能为空的引用文本
- 02:[S] 取消引用可能为空的引用文本
- 03:[S] 不兼容的类型。找到:@Nullable String,需要:@NonNull String
注解包:
javax.annotation.* // JSR 305
edu.umd.cs.findbugs.annotations.* // FindBugs
org.jetbrains.annotations.* // IntelliJ
checkers.nullness.quals.* // Checker Framework
最佳答案
请注意,FindBugs 对待@Nullable 和@CheckForNull 的方式截然不同——前者基本上是在说“我不知道这是否应该允许 null”,而后者则说“这个方法明确地允许 null”。当我们将代码中的所有 @Nullable 全局更改为 @CheckForNull 时,我的团队获得了更有用的 FindBugs 结果,因为后者才是我们真正想要的。
关于java - Java的NPE注解场景和静态分析工具,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2794928/