Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell PMD to ignore @PostConstruct Methods for unused Code

Tags:

java

cdi

ejb

pmd


we have a project which is checked by PMD for violations of e.g. unused private methods. Our problem is that we don't know if it is possible to ignore private Methods which are annotated with @PostConstruct.

The rule is defined as following:

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

Edit:

My goal is to define it once to ignore annotated methods. I would like to prevent writing @SupressWarnings on every method.

like image 229
moz987 Avatar asked Jan 20 '16 15:01

moz987


Video Answer


2 Answers

With the hint and advice from HairyFotr i was able to configure my ruleset to ignore private methods with @PostConstruct.

The rule I had to use is:

<rule ref="rulesets/java/unusedcode.xml/UnusedPrivateMethod">
    <properties> 
        <property name="violationSuppressXPath" 
            value="//ClassOrInterfaceBodyDeclaration/Annotation/MarkerAnnotation/Name[@Image='PostConstruct']" />
    </properties>
</rule>   
like image 188
moz987 Avatar answered Nov 15 '22 23:11

moz987


moz987's answer suppresses all UnusedPrivateMethod violations in a file as soon as there is at least one @PostConstruct annotation present. If you only want to suppress the violations coming from methods with a @PostConstruct annotation and keep the violations from methods without the annotation then you have to prepend the XPath with ancestor:: instead of //.

Note: the example below uses the new rule reference of PMD 6.0.0.

  <rule ref="category/java/bestpractices.xml/UnusedPrivateMethod">
    <properties>
      <property name="violationSuppressXPath"
                value="ancestor::ClassOrInterfaceBodyDeclaration/Annotation/MarkerAnnotation/Name[@Image='PostConstruct']" />
    </properties>
  </rule>
like image 37
Acanda Avatar answered Nov 16 '22 00:11

Acanda