为什么明明使用了未使用的方法却出现 PMD 违规

fed*_*dup 6 java pmd java-11

PMD 失败:...规则:UnusedPrivateMethod 优先级:3 避免未使用的私有方法,例如“printMyString(String)”

private void anyMethod() {
    var myString = "a String";
    printMyString(myString);
}

private void printMyString(String string) {
    System.out.println(string);
}
Run Code Online (Sandbox Code Playgroud)

使用maven这个插件

            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-pmd-plugin</artifactId>
            <version>3.12.0</version>
Run Code Online (Sandbox Code Playgroud)

fed*_*dup 2

这似乎是 PMD 中的一个错误,因为它在通过推断的“var”跟踪变量类型时存在问题。目标方法具有明确定义的参数。

我可以通过禁用特定的 PMD 规则来解决这个问题。在 pom.xml 中,我修改 PMD 插件以使用本地规则文件。

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-pmd-plugin</artifactId>
            <version>3.12.0</version>
            <configuration>
                <linkXRef>false</linkXRef>
                <printFailingErrors>true</printFailingErrors>
                <failOnViolation>true</failOnViolation>
                <rulesets>
                    <ruleset>${basedir}/PMD.xml</ruleset>
                </rulesets>
            </configuration>
            <executions>
                <execution>
                    <goals>
                        <goal>check</goal>
                        <goal>cpd-check</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
Run Code Online (Sandbox Code Playgroud)

以及 PMD.xml 文件(位于项目的根目录中)。

<ruleset xmlns="http://pmd.sourceforge.net/ruleset/2.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="Default Maven PMD Plugin Ruleset" xsi:schemaLocation="http://pmd.sourceforge.net/ruleset/2.0.0 http://pmd.sourceforge.net/ruleset_2_0_0.xsd">
    <description>
        Excluding rules.
    </description>
    <rule ref="category/java/bestpractices.xml">
        <exclude name="UnusedPrivateMethod"/>
    </rule>
</ruleset>
Run Code Online (Sandbox Code Playgroud)