运行PMD v7.11得到空结果,排查Java文件圈复杂度计算问题
问题分析与解决
问题重现
我尝试用PMD v7.11计算Java文件Game.java的圈复杂度,创建了如下规则文件ruleset.xml:
<?xml version="1.0"?> <ruleset name="Custom Rules" 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 https://pmd.sourceforge.io/ruleset_2_0_0.xsd"> <description> My custom rules </description> <rule ref="category/java/design.xml/CyclomaticComplexity"> </rule> </ruleset>
执行命令:
pmd check -f json -R ./ruleset.xml -d Game.java
得到的JSON输出中files字段为空:
{ "formatVersion": 0, "pmdVersion": "7.11.0", "timestamp": "2025-03-07T18:30:29.815+01:00", "files": [], "suppressedViolations": [], "processingErrors": [], "configurationErrors": [] }
错误原因及解决方法
1. PMD 7.x规则引用与命名空间不兼容
PMD 7.x对规则集的命名空间和规则引用格式做了调整,旧的http://pmd.sourceforge.net/ruleset/2.0.0命名空间已过时,规则引用路径也需要改用短ID格式。
修正后的ruleset.xml:
<?xml version="1.0"?> <ruleset name="Custom Rules" xmlns="https://pmd.github.io/pmd/ruleset/2.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://pmd.github.io/pmd/ruleset/2.0.0 https://pmd.github.io/pmd/ruleset_2_0_0.xsd"> <description> My custom rules </description> <rule ref="java-design:CyclomaticComplexity"> <!-- 可选:调整阈值,确保能触发记录 --> <properties> <property name="minimum" value="1"/> </properties> </rule> </ruleset>
2. 默认规则仅在复杂度超标时生成记录
CyclomaticComplexity规则默认阈值为10,只有当方法圈复杂度≥10时,才会生成违规记录,此时文件才会出现在files数组中。如果Game.java所有方法复杂度都低于10,输出自然为空。
如果只是想获取所有方法的圈复杂度数值(无论是否超标),建议使用PMD的metrics命令替代check:
pmd metrics -f json -d Game.java --metric cyclomatic
该命令会直接输出文件中所有方法的圈复杂度数据,文件信息也会正常出现在结果中。
内容的提问来源于stack exchange,提问作者Michael Wahler
相关产品推荐
相关产品推荐

