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

吃可爱长大的小学妹 提交于 2019-12-12 11:39:36

问题



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.


回答1:


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>   



回答2:


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>


来源:https://stackoverflow.com/questions/34903531/how-to-tell-pmd-to-ignore-postconstruct-methods-for-unused-code

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!