15.3.4 PMD

PMD是一款强大的Java源代码分析工具,它能够寻找代码中的问题,包括潜在的bug、无用代码、可优化代码、重复代码以及过于复杂的表达式。关于该工具的详细信息可以访问http://pmd.sourceforge.net/进行了解。

要让Maven在站点中生成PMD报告,只需要配置maven-pmd-plugin如下:


<reporting>

<plugins>

<plugin>

<groupId>org.apache.maven.plugins</groupId>

<artifactId>maven-pmd-plugin</artifactId>

<version>2.5</version>

</plugin>

……

</plugins>

</reporting>


运行mvn site之后,就能得到图15-8所示的PMD报告。

15.3.4 PMD - 图1

图 15-8 PMD报告

需要注意的是,除了PMD报告之外,maven-pmd-plugin还会生成一个名为CPD的报告,该报告中包含了代码拷贝粘贴的分析结果。

PMD包含了大量的分析规则,读者可以访问http://pmd.sourceforge.net/rules/index.html查看这些规则。PMD默认使用的规则为rulesets/basic.xml、rulesets/unusedcode.xml和rulesets/importss.xml。要使用其他的规则,可以配置maven-pmd-plugin插件,如代码清单15-8所示。

代码清单15-8 配置maven-pmd-plugin使用非默认分析规则


<reporting>

<plugins>

<plugin>

<groupId>org.apache.maven.plugins</groupId>

<artifactId>maven-pmd-plugin</artifactId>

<version>2.5</version>

<configuration>

<rulesets>

<ruleset>rulesets/braces.xml</ruleset>

<ruleset>rulesets/naming.xml</ruleset>

<ruleset>rulesets/strings.xml</ruleset>

</rulesets>

</configuration>

</plugin>

</plugins>

</reporting>


maven-pmd-plugin支持聚合报告,只需要如下配置aggregate参数即可:


<reporting>

<plugins>

<plugin>

<groupId>org.apache.maven.plugins</groupId>

<artifactId>maven-pmd-plugin</artifactId>

<version>2.5</version>

<configuration>

<aggregate>true</aggregate>

</configuration>

</plugin>

</plugins>

</reporting>