【问题标题】:Using Conditions in XPath Query在 XPath 查询中使用条件
【发布时间】:2017-04-13 21:06:26
【问题描述】:

我正在尝试为我的存储库编写一个 PMD 规则,我需要所有记录器类都是 log4j 类型。 例如:

代码:

import some;
class Foo{
    Logger log = Logger.getLogger(Foo.class.getName());
    }
}

我的 PMD 规则的 XPath 查询:

(//ImportDeclaration //Name[@Image!='org.apache.log4j.Logger'] ) 
|
( //ClassOrInterfaceBodyDeclaration //FieldDeclaration //Type //ReferenceType //ClassOrInterfaceType[@Image='Logger'])

我在这里测试 Logger 类是否在代码中使用并且它不是 log4j 类型,那么它是违规的。

【问题讨论】:

  • 这个 xpath 查询似乎有一些错误。我想检查是否在一个类中创建了 Logger 对象,那么应该有一个 apache log4j 的导入。但我不能把和运算符或 if..else 条件相同。

标签: java logging xpath pmd


【解决方案1】:

由于可以有星号导入、相同的包访问以及简单且完全限定的名称,我建议您使用typeresolution

//ClassOrInterfaceBodyDeclaration//FieldDeclaration//Type//ReferenceType//ClassOrInterfaceType[ends-with(@Image, 'Logger') and not(typeof(@Image, 'org.apache.log4j.Logger', 'Logger'))]

最终规则将表述为:

<rule name="All Loggers must be Log4J Loggers"
      message="All Loggers must be Log4J Loggers"
      class="net.sourceforge.pmd.lang.rule.XPathRule"
      language="java"
      typeResolution="true">
    <description>
        All Loggers must be Log4J Loggers
    </description>
    <priority>3</priority>
    <properties>
        <property name="xpath">
            <value>
    //ClassOrInterfaceBodyDeclaration//FieldDeclaration//Type//ReferenceType//ClassOrInterfaceType[ends-with(@Image, 'Logger') and not(typeof(@Image, 'org.apache.log4j.Logger', 'Logger'))]
            </value>
        </property>
    </properties>
</rule>

注意rule 节点上的typeResolution="true" 属性。还要确保正确填充 auxclasspath 以进行类型解析。 Gradle 会自动完成,在 Maven 上你必须 enable it through configuration,在 Ant 上你需要手动传递 auxclasspath

最后一点,这条规则只会查找字段,其他记录器的未使用导入/星号导入将不会被检测到,即使可以添加它们,我也会简单地使用 the existing rule 来处理未使用的进口。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-15
    • 1970-01-01
    • 2019-12-14
    • 2020-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多