我正在尝试用 Java 编写自定义 PMD 规则。我创建了一个如下所示的自定义规则集:
<?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>
My custom rules
</description>
<rule name="CustomRule"
message="Custom message"
class="mwe.CustomRule">
<description>
Custom description
</description>
<priority>3</priority>
</rule>
</ruleset>
我pmd.bat
使用这个 Java 类调用:
package mwe;
import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;
public class PmdStarter {
public static void main(String[] args) {
callPmd();
}
public static void callPmd() {
String pmdPath = "pmd-src-5.0.5/bin/pmd.bat";
String checkThisCode = "checkThisCode/";
String customRuleSet = "pmd-src-5.0.5/src/main/resources/rulesets/java/customRules.xml";
String[] command = { pmdPath, "-dir", checkThisCode, "-rulesets",
customRuleSet };
ProcessBuilder pb = new ProcessBuilder(command);
try {
InputStream is = pb.start().getInputStream();
String output = convertStreamToString(is);
is.close();
System.out.println(output);
} catch (IOException e) {
e.printStackTrace();
}
}
static String convertStreamToString(InputStream is) {
Scanner s = new Scanner(is);
s.useDelimiter("\\A");
String streamContent = s.hasNext() ? s.next() : "";
s.close();
return streamContent;
}
}
不幸的是,找不到我用 Java 编写的自定义规则;这是来自 PmdStarter 的消息:
找不到类 mwe.CustomRule
这是我的(最小)自定义规则:
package mwe;
import net.sourceforge.pmd.lang.java.ast.ASTWhileStatement;
import net.sourceforge.pmd.lang.java.rule.AbstractJavaRule;
public class CustomRule extends AbstractJavaRule {
public Object visit(ASTWhileStatement node, Object data) {
System.out.println("Hello PMD");
return data;
}
}
这是我在 Eclipse 中的项目结构:
我在这里读到这种错误似乎是类路径错误。读完这篇文章后,我把它放在CustomRule.class
项目中的几个目录中,希望 PMD 能找到它,但这是徒劳的。
我的问题是:我怎样才能让 PMD 执行我的CustomRule
?