Amit
Amit

Reputation: 21

Custom Rules With PMD - Passing values to a rule at runtime

My requirement is to parse java files and find the classes or interfaces which implement a particular interface. Hence I started with implementing custom rules in PMD. I was able to write an XPath expression to search the classes & interfaces but was not able to figure out the right way to pass the interface name for which the search is to be done to the XPath rule. One way was to define a property and update the xml file before invoking PMD.

<rule name="Implement or extend an interface"
    message="Implement or extend an interface"
    class="net.sourceforge.pmd.rules.XPathRule">
<description>
This rule will help us to find out all the classes/interface which implement a particular interface
</description>
<properties>
    <property name="xpath">
        <value>
        <![CDATA[
        //ImplementsList/ClassOrInterfaceType[@Image=$interfaceName] |
        //ExtendsList/ClassOrInterfaceType[@Image=$interfaceName]
        ]]>
        </value>
    </property>
    <property name="interfaceName">
        <value>Should be set at run time</value>
    </property>
</properties>
<example>

The problem with the above approach is that PMD cannot be invoked in threads since the xml would be shared.

Has anyone faced such a problem with PMD where values are to be passed to a rule at runtime?

Upvotes: 2

Views: 1140

Answers (1)

Jeanne Boyarsky
Jeanne Boyarsky

Reputation: 12266

If you want to be able to use different values in an XPath rule, you'd need to have multiple copies of the rule - one for each value. An alternative using PMD is to use a Java rule. It can even call the XPath. The difference is that Java is runtime so can get values later or loop through a set of values.

Upvotes: 1

Related Questions