NPE注释场景和Java静态分析工具 [英] NPE annotation scenarios and static-analysis tools for Java

查看:196
本文介绍了NPE注释场景和Java静态分析工具的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是一些可以抛出NullPointerException的代码片段。

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;

    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.

这里我的结果

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()可能为null

Checker Framework(1.0.7):

Checker Framework (1.0.7):


  • 01:[S]取消引用可能为空的引用文本

  • 02:[S]取消引用可能为空的引用文本

  • 03: [S]不兼容的类型。发现:@Nullable字符串,必填:@NonNull字符串

注释包:

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


推荐答案

请注意,FindBugs对待@Nullable和@CheckForNull的方式完全不同 - 前者基本上是在说我不知道这是否应该允许null和后者说这种方法明确允许空值。当我们在代码中将所有@Nullable全局更改为@CheckForNull时,我的团队有更多有用的FindBugs结果,因为后者是我们真正的意思。

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.

这篇关于NPE注释场景和Java静态分析工具的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆