Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint

4.2. Using PMD with Ant

Ant is the most widely used build tool for Java. Naturally, there is a PMD plug-in for Ant. Not surprisingly, the command-line arguments given earlier map fairly directly to attributes in the Ant project file. Here's a simple example extracted from our build.xml:

<target name="pmd">
     <taskdef name="pmd" classname="net.sourceforge.pmd.ant.PMDTask"
            classpathref="full.classpath"/>
     <pmd shortFilenames="true">
           <ruleset>basic,imports</ruleset>
           <formatter type="text" toFile="pmd-ant-results.txt"/>
           <fileset dir="src">
                 <include name="**/*.java"/>
           </fileset>
     </pmd>
</target>

There are many tasks that are known to Ant, but PMD's isn't one of them, so define it with <taskdef>; the PMDTask class is called when the <pmd> task is being run. There are half a dozen attributes that can be added to the <pmd> task; this example only uses shortFileNames. There are another set of elements that can be nested, including PMD's <ruleset> and <formatter>, which have the same meanings as the equivalent command-line parameters, and the standard Ant fileset. Fileset elements are used a lot in Ant scripts; this one is fairly simple and collects all the Java source files in all the directories and subdirectories under src. This list of files is made available to the <pmd> task's class at runtime.

The formatter element obviously tells how to format the results. The text formatter produces a nice concise report, like this:

intro/Action.java:30     An empty statement (semicolon) not part of a loop
intro/Action.java:30     Avoid empty if statements

If you want a fancier HTML report to show your boss (or to embarrass your colleagues), you can use the "html" formatter, or the "xml" formatter with a style sheet to let you format it the way you like. In between is the "htmlsummary" formatter, which produces a less-voluminous HTML formatted report. For more information on the PMD Ant task see the Ant Task Page (http://pmd.sourceforge.net/ant-task.html).