如何使用PMD忽略短变量规则中的“id”

时间:2013-12-23 10:26:10

标签: java eclipse pmd

我正在使用Eclipse的Eclipse PMD插件(版本4.0.2)(Eclipse Kepler Java EE)。我已经配置了一个命名规则:ShortVariable

"id""e"等参数外,此方法正常。我希望PMD忽略这些。所以我搜索了一种忽略某些参数的方法。我找到了this link(虽然它是用于phpmd)并尝试过,但我似乎无法让它工作。我的配置文件看起来像这样(XML):

<?xml version="1.0"?>
<ruleset name="My PMD ruleset"
 xmlns="http://pmd.sourceforge.net/ruleset/2.0.0"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://pmd.sourceforge.net/ruleset/2.0.0 http://pmd.sourceforge.net/ruleset_2_0_0.xsd">
    <description>
        My PMD
    </description>
    <rule ref="rulesets/java/naming.xml/ShortVariable">
        <property name="exceptions" value="id" />
    </rule>
</ruleset>

当我尝试使用eclipse插件导入此规则集时,它显示没有可能导入的规则。 有什么想法吗?

2 个答案:

答案 0 :(得分:12)

我找到了问题here的解决方案。

生成的xml如下所示:

<?xml version="1.0"?>
<ruleset name="My PMD ruleset"
 xmlns="http://pmd.sourceforge.net/ruleset/2.0.0"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://pmd.sourceforge.net/ruleset/2.0.0 http://pmd.sourceforge.net/ruleset_2_0_0.xsd">
    <description>
        My PMD
    </description>
    <rule ref="rulesets/java/naming.xml/ShortVariable">
        <properties>
            <property name="xpath">
                <value>
                    //VariableDeclaratorId[(string-length(@Image) &lt; 3) and (not (@Image='id'))]
                    [not(ancestor::ForInit)]
                    [not((ancestor::FormalParameter) and (ancestor::TryStatement))]
                </value>
            </property>
        </properties>
    </rule>
</ruleset>

为了能够忽略更多变量名,请重复以下部分:

and (not (@Image='myVariableToIgnore'))

答案 1 :(得分:3)

下面的XML对PHP工具PHPMD 2.2.3

有效
<?xml version="1.0"?>
<!DOCTYPE ruleset>
<ruleset
    name="My PMD ruleset for symfony 2.5"
    xmlns="http://pmd.sourceforge.net/ruleset/2.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://pmd.sourceforge.net/ruleset/2.0.0 http://pmd.sourceforge.net/ruleset_2_0_0.xsd"
>

    <rule ref="rulesets/unusedcode.xml" />
    <rule ref="rulesets/codesize.xml" />
    <rule ref="rulesets/cleancode.xml" />
    <rule ref="rulesets/controversial.xml" />
    <rule ref="rulesets/design.xml" />
    <rule ref="rulesets/naming.xml">
       <exclude name="ShortVariable" />
    </rule>
    <rule ref="rulesets/naming.xml/ShortVariable">
        <properties>
            <property name="exceptions" value="id,em" />
        </properties>
    </rule>
</ruleset>