【问题标题】:PMD - skip checking methods annotaded by @PostConstruct or @PreDestroyPMD - 跳过由@PostConstruct 或@PreDestroy 注释的检查方法
【发布时间】:2017-12-14 14:41:21
【问题描述】:

我有以下课程:

import javax.annotation.PostConstruct;

public class PmdUnusedMethod {

    private void unusedMethod() {
    }

    @PostConstruct
    private void postConstructAnnotatedMethod() {
    }
}

并定义 PMD 规则集:

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

在这种情况下,PMD 向我报告两个关于未使用方法(“unusedMethod”和“postConstructAnnotatedMethod”)的错误,但我想忽略使用@PreDestroy 和@PostConstruct 注释的方法的规则“UnusedPrivateMethod”。

我知道我可以这样做:

<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>

但在这种情况下,PMD 跳过检查此规则以检查类中所有方法是否包含我的注释,而不仅仅是使用 @PostConstruct 注释的方法。我希望在检查代码后,我的“unusedMethod”只有错误,PMD 不会通知有关“postConstructAnnotatedMethod”的错误。

我想做这样的事情:

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

只跳过带有所需注释的方法,而不是所有方法。

另外,我不想用许多 @SuppressWarnings("PMD.UnusedPrivateMethod") 注释污染我的代码。

【问题讨论】:

  • 感谢分享@SuppressWarnings("PMD.UnusedPrivateMethod") - 这对我有用(不想碰我们的 pmd 规则集)

标签: java pmd


【解决方案1】:

抑制XPath是以违规所在的节点为起点执行的,因此您可以简单地“上去一个方法,并检查注释”。

例如:

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

【讨论】:

  • 感谢您的回复,但这并不能解决我的问题。将此节点添加到我的 ruleset.xml 后,我仍然有两条关于未使用方法的消息。对于未使用的方法和 postConstructAnnotatedMethod。
  • 我正在即时编写 xpath。我刚刚更新了它,它现在应该可以工作了。
  • PMD 在整个类中禁用此规则,并在任何方法上使用注释 @PostConstruct。我只想在带注释的方法上禁用此规则。我在我的问题中描述了它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-01
  • 2019-12-16
  • 1970-01-01
  • 2018-02-14
  • 2017-08-04
相关资源
最近更新 更多