44

使用FindBugs对Java代码进行静态分析 - 简书

 4 years ago
source link: https://www.jianshu.com/p/4fd821fa9854?
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
0.2812019.08.18 08:48:24字数 442阅读 504

FindBugs

FindBugs是一个Java静态分析工具,用来检查类或者jar文件,查找代码可能存在的问题。
FindBugs官网地址:http://findbugs.sourceforge.net/
检测完成后会生成一份详细的报告,借助这份报告可以找到潜在的Bug,比如NullPointException,还可以检查特定的资源没有关闭,例如:查询数据库没有调用Cursor.close()等。
如果采用人工的方式很难发现类似的bug,有一些Bug没有发现的情况下,直到运行时才出现。
FindBugs可以自动化化的分析代码,帮助我们提高代码质量。
FindBugs操作的是Java字节码,不是源代码。

Grade配置

apply plugin: "findbugs"

findbugs {
    ignoreFailures = true
    toolVersion = "3.0.1"
    reportLevel="high"
   effort = "max"
}

ignoreFailures的配置在有Bug报告的情况,是否返回错误,设置为true的情况下会忽略错误,设置为false有错误信息时会立即中断。
潜在错误可分为三个等级,它们是在reportLevel中进行设置:

  • medium

默认为medium
effort:是分析级别,有三个值可以设置: max,default,min。更高的级别提高了分析的精度,同时也会运行更长的时间,以及消耗更多的内存。

运行FindBugs

运行命令gradle check可以直接运行findBugs,它会运行两个任务:

  • findbugsMain
  • findbugsTest

也可以单独运行命令:

gradle findbugsMain
gradle findbugsTest

生成的报告默认的目录在build/reports/findbugs中,也可以通过reportsDir对生成文件的目录进行设置。

生成文件格式

FindBugs的报告文件默认是xml格式,生成html格式,需要配置:

tasks.withType(FindBugs) {
    reports {
        xml.enabled false
        html.enabled true
    }
}

Android-使用FindBugs


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK