这里有一些可能会抛出NullPointerException的代码片段。
01:
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] 参数必须为nonnull但标记为nullable
- 02: [F] 未报告
- 03: [F] 未报告
IntelliJ IDE 9.0.2(Community edition):
- 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
@Nullable
和@NonNull
注释使用您想要的任何注释。例如,您可以使用FindBugs注释。这样,您可以在IDE中看到与FindBugs捕获的相同错误。 - undefined