本文将向您介绍 SpotBugs 实用程序项目,它可以帮助您发现代码中可能变成运行时错误的 Java“BUG模式”。
首先,让我们看看 SpotBugs 是如何工作的。此工具使用定义了一组错误模式,将使用检测器在您的代码中进行扫描。反过来,每个 Bug 模式都有不同的 Categories。
默认情况下,SpotBugs 在您的代码中搜索 allBug 模式 并包括 allCategories。但是,您可以选择过滤一组错误模式、项目中的类/方法选择以及特定类别的错误模式。
例如,您可以选择仅扫描特定的错误模式,如下所示,其中异常被捕获而不是抛出
try {
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
另一方面,您可以选择仅扫描属于 PERFORMANCE 类别的错误模式。
您可以使用 Detectors 检测错误模式。检测器列表可在此处获得:https://spotbugs.readthedocs.io/en/latest/detectors.html
为了安装 SpotBugs,您有多种选择:您可以从 GitHub 下载最新版本:https://github.com/spotbugs/spotbugs/
当您从源代码安装项目时,您将能够从命令行调用 SpotBugs。例如:
java -jar $SPOTBUGS_HOME/lib/spotbugs.jar options...
另一方面,您也可以将 SpotBugs 作为 Maven / Gradle / Ant 或 Eclipse 插件运行。
在本文的下一部分中,我们将展示如何在 Maven 项目中使用 SpotBugs。
为了在 Maven 项目中使用此工具,您只需将其 Maven 插件添加到 pom.xml 的报告部分:
<reporting>
<plugins>
<plugin>
<groupId>com.github.spotbugs</groupId>
<artifactId>spotbugs-maven-plugin</artifactId>
<version>4.7.1.1</version>
</plugin>
</plugins>
</reporting>
报告插件将在 Maven 站点目标中运行。因此,您可以按如下方式运行它:
mvn compile site
然后,验证您的 Maven 日志中是否正在生成 SpotBugs 报告:
[INFO] Generating "SpotBugs" report --- spotbugs-maven-plugin:4.7.1.1:spotbugs
最后,您会在项目的 target/site 文件夹下找到 spotbugs.htmlreport:
[francesco@fedora tamutils]$ tree target/site
target/site
├── css
├── dependencies.html
├── dependency-info.html
├── index.html
├── plugin-management.html
├── plugins.html
├── project-info.html
├── project-reports.html
├── spotbugs.html
└── summary.html
打开 SpotBugs HTML 页面以检查您的项目的报告:
HTML 报告包含按类别分组的报告中包含的类列表。
在我们的基本示例中,SpotBugs 将扫描所有类别中所有可能的错误模式。要将过滤器引入这些选项,您可以使用 XML 过滤器文件。例如,以下插件配置为您的项目引入了包含过滤器和排除过滤器:
<plugin>
<groupId>com.github.spotbugs</groupId>
<artifactId>spotbugs-maven-plugin</artifactId>
<version>4.7.1.1</version>
<configuration>
<includeFilterFile>myfilter-include.xml</includeFilterFile>
<excludeFilterFile>myfilter-exclude.xml</excludeFilterFile>
</configuration>
</plugin>
例如,以下 myfilter-include.xml 定义了一个错误模式(“OS_OPEN_STREAM”:方法可能无法关闭流),该模式适用于类 com.foobar.MyClass 在其方法 writedataToFile 中:
<?xml version="1.0" encoding="UTF-8"?>
<FindBugsFilter>
<Match>
<Class name="com.foobar.MyClass" />
<Method name="writeDataToFile" />
<Bug pattern="OS_OPEN_STREAM" />
</Match>
</FindBugsFilter>
另一方面,以下 XML 过滤器文件将 PERFORMANCE 类别中的所有错误模式定义为匹配过滤器:
<?xml version="1.0" encoding="UTF-8"?>
<FindBugsFilter>
<Match>
<Bug category="PERFORMANCE" />
</Match>
</FindBugsFilter>
最后,我们将提到如何将该工具安装为 Eclipse Plugin。你可以通过两种方式做到这一点:
重新启动 Eclipse 后,您将能够在您的项目中激活 SpotBugs 选项。您需要做的就是右键单击您的项目。然后,选择选项,例如 Find Bugs:
SpotBugs 将执行,问题标记(显示在源窗口中,也显示在 Eclipse 问题视图中)将指向代码中可能存在错误模式实例的位置。
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : http://www.mastertheboss.com/java/how-to-spot-java-bugs-with-spotbugs/
内容来源于网络,如有侵权,请联系作者删除!