开发者

NPE annotation scenarios and static-analysis tools for Java

开发者 https://www.devze.com 2022-12-29 09:48 出处:网络
Here is a number of code snippets that can throw NullPointerException. 01: public void m1(@Nullable String text) {

Here is a number of code snippets that can throw 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;

 开发者_StackOverflow社区   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.
}

Different people have access to different static-analysis tools. It would be nice to collect information, what tools are able to detect and report the issues, and what are failing. Also, if you have your own scenarious, please, publish them.

Here my results

FindBugs (1.3.9):

  • 01: [S] Parameter must be nonnull but is marked as nullable
  • 02: [F] not reported
  • 03: [F] not reported

IntelliJ IDE 9.0.2 (Community edition):

  • 01: [S] Method invocation text.toLowerCase() may produce java.lang.NullPointerException
  • 02: [S] Method invocation text.toLowerCase() may produce java.lang.NullPointerException
  • 03: [S] Argument getText() might be null

Checker Framework (1.0.7):

  • 01: [S] dereference of possibly-null reference text
  • 02: [S] dereference of possibly-null reference text
  • 03: [S] incompatible types. found: @Nullable String, required: @NonNull String

Annotations packages:

javax.annotation.* // JSR 305
edu.umd.cs.findbugs.annotations.* // FindBugs
org.jetbrains.annotations.* // IntelliJ
checkers.nullness.quals.* // Checker Framework


Please note that FindBugs treats @Nullable and @CheckForNull quite differently -- the former is basically saying "I have no idea whether this is supposed to allow null or not" and the latter says "This method explictly allows nulls". My team had much more useful FindBugs results when we globally changed all @Nullable to @CheckForNull in our code, since the latter is what we really had meant.

0

精彩评论

暂无评论...
验证码 换一张
取 消