Search code examples
javaxpathpmd

How can getters/setters be ignored in the PMD CommentRequired rule?


I want to use PMDs CommentRequired rule, but don't want it to be applied to java bean getters/setters.

Based on this answer I tried the following configuration:

<rule ref="rulesets/java/comments.xml/CommentRequired">
    <properties>
        <property name="violationSuppressXPath" value="./ancestor::MethodDeclaration/MethodDeclarator/NodeToken[@tokenImage='(get|is|set).*']"/>
        <property name="fieldCommentRequirement" value="Ignored"/>
    </properties>
</rule>

However PMD still reports that some getters in my code need a comment.

What is the correct XPath expression to suppress the rule for getters/setters and on which schema are the PMD XPath expressions based upon?


Solution

  • After reading the PMD XPath rule tutorial and playing around with the PMD Designer the following does work for me:

    <rule ref="rulesets/java/comments.xml/CommentRequired">
        <properties>
            <property name="violationSuppressXPath" value="//ClassOrInterfaceBodyDeclaration/MethodDeclaration/MethodDeclarator[matches(@Image,'(get|is|set)[\p{Lu}].*') and not(FormalParameters/FormalParameter)]"/>
            <property name="fieldCommentRequirement" value="Ignored"/>
        </properties>
    </rule>
    

    To get a better grasp on the AST that PMD is using, one can have a look at the javadoc of it: http://pmd.sourceforge.net/pmd-5.1.0/apidocs/net/sourceforge/pmd/lang/java/ast/package-summary.html