Creating Custom Ant Tasks

As you've seen in the earlier chapters of this tutorial, Ant is a valuable addition to the software development process and faciliates project bulding. Fundamentally, Ant is designed to execute tasks. We've seen tasks like compiling source code, automating code generation using XDoclet, and gathering code into a JAR, among others. What if we could create our own task for Ant to execute? The key here is developing a task that isn't just a nice-to-have execution that could be accomplished with the standard <java> task. In other words, if we have an app that is launched by Java and just accepts a few command-line options, then we can use the <java> task instead. Suppose, however, we want to create a new <task> that can influence the app directly. This task might involve outputting results from the app in XML format. The output would be accomplished by an Ant task and not the app itself. In this chapter we look at an example task as well as how Ant works internally.

How Ant Works

When we create an Ant build script, we include some number of targets, which in turn include tasks. For example, consider the Ant build script in the following listing.

<?xml version="1.0 ?>
 description="clean up the output directories and jar.">
 <delete dir="${local_outdir}" />
 <delete file="${model_jar}" />
 <target depends="init" description="prepare the output directory.">
 <mkdir dir="${build}" />
 <mkdir dir="${lib}" />
 <target depends="prepare" description="compile the Java source.">
 <javac srcdir="./src" destdir="${build}" />
 <target depends="compile"
 description="package the Java classes into a jar.">
 <jar jarfile="${model_jar}"
 basedir="${build}" />
 <target depends="clean,package" description="perform all targets."/> </project>

Here we have several targets that will be executed in a specific hierarchy. The targets are designed for this purpose. What's important are the tasks within the targets, such as <jar>, <mkdir>, <delete>, and <javac>.

When the Ant build loop encounters a task, it relinquishes control to a specific class created for the task. In our example build script, the tasks are built into Ant itself; therefore, you don't see any <taskdef> elements, which would define a class to be used when evaluating the task. Ant just knows about <jar>, <mkdir>, <delete>, and <javac>. In the remainder of this chapter we show you how to build your own task.