How to make a new rule set

Say you want to pick specific rules from various rule sets and customize them. You can do this by making your own rule set.

Create a new ruleset.xml file

Use one of the current rulesets as an example. Copy and paste it into your new file, delete all the old rules from it, and change the name and description. Like this:

<?xml version="1.0"?>
<ruleset name="customruleset">
  <description>
  This ruleset checks my code for bad stuff
  </description>
</ruleset>
    

Add some rule references to it

After you add these references it'll look something like this:

<?xml version="1.0"?>
<ruleset name="customruleset">

  <description>
  This ruleset checks my code for bad stuff
  </description>

  <!-- We'll use the entire 'strings' ruleset -->
  <rule ref="rulesets/strings.xml"/>

  <!-- Here's some rules we'll specify one at a time -->
  <rule ref="rulesets/unusedcode.xml/UnusedLocalVariable"/>
  <rule ref="rulesets/unusedcode.xml/UnusedPrivateField"/>
  <rule ref="rulesets/imports.xml/DuplicateImports"/>
  <rule ref="rulesets/basic.xml/UnnecessaryConversionTemporary"/>

  <!-- We want to customize this rule a bit, change the message and raise the priority  -->
  <rule
   ref="rulesets/basic.xml/EmptyCatchBlock"
   message="Must handle exceptions">
     <priority>2</priority>
  </rule>

  <!-- Note we want everything from braces.xml except the WhileLoopsMustUseBracesRule -->
  <rule ref="rulesets/braces.xml">
    <exclude name="WhileLoopsMustUseBracesRule"/>
  </rule>
</ruleset>
    

Notice that you can customize individual referenced rules. Everything but the class of the rule can be overriden in your custom ruleset.

Excluding rules from a ruleset

You can also make a custom ruleset that excludes rules, like this:

<?xml version="1.0"?>
<ruleset name="mybraces">
 <description>Just the braces rules I like</description>
 <rule ref="rulesets/braces.xml">
  <exclude name="WhileLoopsMustUseBracesRule"/>
  <exclude name="IfElseStmtsMustUseBracesRule"/>
 </rule>
</ruleset>
            

Reference it in your Ant task

You can specify the full path to your custom ruleset name alongside of the built-in PMD rulesets - like this:

    <pmd rulesetfiles="/home/tom/data/pmd/pmd/rulesets/favorites.xml,rulesets/unusedcode.xml">
        <formatter type="xml" toFile="foo.xml"/>
        <fileset dir="/home/tom/data/pmd/pmd/src">
            <include name="**/*.java"/>
        </fileset>
    </pmd>

To see it in your IDE, add it to rulesets/rulesets.properties

At least, that's the way some of the IDE plugins do it. Some have other ways of adding custom rulesets.

Send us feedback

If you have suggestions on clarifying this document, please post them to the forum. Thanks!