2
votes

I have the following class:

import javax.annotation.PostConstruct;

public class PmdUnusedMethod {

    private void unusedMethod() {
    }

    @PostConstruct
    private void postConstructAnnotatedMethod() {
    }
}

and defined PMD rule-set:

<rule ref="rulesets/java/unusedcode.xml"/>

In that case PMD report me two errors about unused methods ("unusedMethod" and "postConstructAnnotatedMethod"), but I want to ignore rule "UnusedPrivateMethod" for methods annotated with @PreDestroy and @PostConstruct.

I know I could do something like this:

<rule ref="rulesets/java/unusedcode.xml">
        <exclude name="UnusedPrivateMethod"/>
    </rule>
    <rule ref="rulesets/java/unusedcode.xml/UnusedPrivateMethod">
        <properties>
            <property name="violationSuppressXPath"
                      value="//ClassOrInterfaceBodyDeclaration/Annotation/MarkerAnnotation/Name[@Image='PostConstruct']"/>
        </properties>
    </rule>

But in this case PMD skip to check this rule for all methods in class contains my annotation, not only for method annotated with @PostConstruct. I expect that after check code, I have only error with my "unusedMethod" and PMD will not notify errors about "postConstructAnnotatedMethod".

I want to do something like this:

<rule ref="rulesets/java/unusedcode.xml/UnusedPrivateMethod">
    <properties>
        <property name="violationSuppressXPath"
                  value="//MethodDeclaration/Annotation/Name[@Image='PostConstruct']"/>
    </properties>
</rule>

to skip only methods annotated with desired annotation, not all methods.

Also I don't want to pollute my code with many @SuppressWarnings("PMD.UnusedPrivateMethod") annotations.

1
Thanks for sharing @SuppressWarnings("PMD.UnusedPrivateMethod") - this works for me (didn't want to touch our pmd ruleset) - user1697575

1 Answers

0
votes

The suppression XPath is executed taking the node where the violation lies as starting point, so you can simply "go up to a method, and check the annotations".

For instance:

<rule ref="rulesets/java/unusedcode.xml/UnusedPrivateMethod">
    <properties>
        <property name="violationSuppressXPath"
                  value="./ancestor::ClassOrInterfaceBodyDeclaration/Annotation/MarkerAnnotation/Name[@Image='PostConstruct']"/>
    </properties>
</rule>