简体   繁体   English

PMD-跳过@PostConstruct或@PreDestroy注释的检查方法

[英]PMD - skip checking methods annotaded by @PostConstruct or @PreDestroy

I have the following class: 我有以下课程:

import javax.annotation.PostConstruct;

public class PmdUnusedMethod {

    private void unusedMethod() {
    }

    @PostConstruct
    private void postConstructAnnotatedMethod() {
    }
}

and defined PMD rule-set: 并定义了PMD规则集:

<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. 在那种情况下,PMD向我报告了两个关于未使用方法的错误(“ unusedMethod”和“ postConstructAnnotatedMethod”),但是对于@PreDestroy和@PostConstruct注释的方法,我想忽略规则“ UnusedPrivateMethod”。

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. 但是在这种情况下,PMD跳过了检查该规则的步骤,以检查类中包含我的注释的所有方法,而不仅限于使用@PostConstruct注释的方法。 I expect that after check code, I have only error with my "unusedMethod" and PMD will not notify errors about "postConstructAnnotatedMethod". 我希望检查代码后,我的“ unusedMethod”只有错误,而PMD不会通知有关“ 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. 另外,我也不想使用许多@SuppressWarnings("PMD.UnusedPrivateMethod")注释来污染我的代码。

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". 禁止XPath以违反行为所在的节点为起点执行,因此您可以简单地“上一个方法,并检查注释”。

For instance: 例如:

<rule ref="rulesets/java/unusedcode.xml/UnusedPrivateMethod">
    <properties>
        <property name="violationSuppressXPath"
                  value="./ancestor::ClassOrInterfaceBodyDeclaration/Annotation/MarkerAnnotation/Name[@Image='PostConstruct']"/>
    </properties>
</rule>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM