PMD - skip checking methods annotaded by @PostConstruct or @PreDestroy

核能气质少年 提交于 2019-12-11 03:23:40

问题


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:


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>


来源:https://stackoverflow.com/questions/47815987/pmd-skip-checking-methods-annotaded-by-postconstruct-or-predestroy

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