Search code examples
javastatic-analysispmdsuppress-warningsstatic-code-analysis

Suppress PMD violation in certain classes


I've got ViewState POJO classes which have constructors with many parameters. Problem is that PMD is throwing ExcessiveParameterList violation on them.

Now I'm trying to suppress this violation for all classes which end with ViewState.java (e.g. in DashboardViewState.java). I've added this to my rules-pmd.xml:

<rule ref="category/java/design.xml/ExcessiveParameterList">
    <properties>
        <!--Ignore ExcessiveParameterList on ViewState classes -->
        <property name="violationSuppressXPath" value="//ClassOrInterfaceDeclaration['*ViewState.java']"/>
    </properties>
</rule>

Problem is that this will suppress all violations against ExcessiveParameterList no matter in which class. What am I doing wrong?


Solution

  • this is a duplicate of this question, though since nobody upvoted my answer I can't flag this as a duplicate.

    See https://stackoverflow.com/a/56460327/6245827 for details about why your expression suppresses all violations of the rule.

    The solution here is to test the @Image attribute of the ClassOrInterfaceDeclaration, and not using //, but rather an ancestor check:

    ./ancestor::ClassOrInterfaceDeclaration[contains(@Image, 'ViewState')]
    

    XPath 1.0 doesn't support regex, so you're limited to doing a contains check like here, or mimicking an ends-with function with substring, like explained in this answer