PMD
)是一種開源分析源代碼錯誤的工具,它會發現一些常見的編程缺陷,好比未使用的變量,空的catch塊,沒必要要的對象建立等。它支持Java,JavaScript等。
此外,用戶還能夠本身定義規則,檢查Java代碼是否符合某些特定的編碼規範。
基於PMD,阿里巴巴基於本身的Java編碼規範實現了P3C-PMDhtml
檢查規則爲xml格式,注意配置中指定的配置文件在jra包中,須要p3c包編譯到項目中才行正確引入:java
dependencies { pmd "com.alibaba.p3c:p3c-pmd:2.0.0" }
xml配置文件以下:android
<?xml version="1.0"?> <ruleset name="Custom ruleset" xmlns="http://pmd.sourceforge.net/ruleset/2.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://pmd.sourceforge.net/ruleset/2.0.0 http://pmd.sourceforge.net/ruleset_2_0_0.xsd"> <description> 自定義Rule set </description> <!-- 引入PMD制定的Rule, 來源於https://github.com/pmd/pmd/tree/master/pmd-java/src/main/resources/rulesets/java --> <rule ref="rulesets/java/android.xml"> <exclude name="CallSuperLast"/> </rule> <rule ref="rulesets/java/basic.xml"> <exclude name="CollapsibleIfStatements"/> </rule> <rule ref="rulesets/java/clone.xml"/> <rule ref="rulesets/java/finalizers.xml"/> <rule ref="rulesets/java/imports.xml"/> <rule ref="rulesets/java/javabeans.xml"/> <rule ref="rulesets/java/optimizations.xml"> <exclude name="LocalVariableCouldBeFinal"/> <exclude name="MethodArgumentCouldBeFinal"/> </rule> <rule ref="rulesets/java/sunsecure.xml"/> <rule ref="rulesets/java/unnecessary.xml"> <exclude name="UselessParentheses"/> </rule> <!-- 引入阿里的Rule, 來源於 alibaba/p3c --> <rule ref="rulesets/java/ali-comment.xml"> </rule> <rule ref="rulesets/java/ali-concurrent.xml"> </rule> <rule ref="rulesets/java/ali-constant.xml"> </rule> <rule ref="rulesets/java/ali-exception.xml"> </rule> <rule ref="rulesets/java/ali-flowcontrol.xml"> </rule> <rule ref="rulesets/java/ali-naming.xml"> </rule> <rule ref="rulesets/java/ali-oop.xml"> </rule> <rule ref="rulesets/java/ali-orm.xml"> </rule> <rule ref="rulesets/java/ali-other.xml"> </rule> <rule ref="rulesets/java/ali-set.xml"> </rule> </ruleset>
該配置文件放在etc/pmd/relest.xml
下git
apply plugin: "pmd" pmd { toolVersion = '6.17.0' ignoreFailures = true ruleSetConfig = resources.text.fromFile("etc/pmd/ruleset.xml") } dependencies { pmd "com.alibaba.p3c:p3c-pmd:2.0.0" ... }
其中ignoreFailures
若是設置爲true表示規範檢查即便是不經過gradle check
也不會報錯,設置爲false時,代碼規範檢查必須經過才check的時候纔不會報錯。github
能夠經過命令:編程
gradle check
運行pmdMain
,它會檢查__src/main/java__下的代碼,還會運行pmdTest
,它會檢查__src/main/test__下的代碼。
也能夠分別運行這兩個命令:app
gradle pmdMain gradle pmdTest
運行以後的結果在目錄 build/reports/pmd
中的main.html,test.html文件中less