A Skeleton Task Example

As you might have guessed, all Ant tasks are just Java classes either built into Ant or specified by the <taskdef> element. The only requirement of the class is that it have an execute() method that can be called by the Ant app. So, we might design a new class like the following:

public class NewTask {
 public void execute() {
 // do something

With this class we could have an Ant task like this:

<taskdef ame="todo" classname="">

Of course, a real Ant task has various attributes and conditions, like unless, which we probably want to be able to access from the Ant build script. In order to have access to this information, we must extend For example:

public class NewTask extends{
 public void execute() {
 // do something

The Task class gives us the ability to access the varous attributes contained in the build script. The methods available in the Ant Task class are shown in the following table.



void execute()

Called by Ant to execute the work of the task.

java.lang.String getDescription()

Returns the description of this task.

Location getLocation()

Returns a Location object specifying where the Ant task appears in the build script.

Target getOwningTarget()

Returns a Target object containing the parent of this Ant task.

Project getProject()

Returns a Project object for this task.

java.lang.String getTaskName()

Gets the name of this task.

Void init()

Called by this Ant tasks project.

void log(String msg)

Logs a message.

void log(String msg, int msgLevel)

Logs a message.

void setDescription(String desc)

Sets the description.

void setLocation(Location location)

Sets the file location of this task.

void setOwningTarget(Target target)

Sets the target of this task.

void setTaskName(String name)

Sets the name of this task

As you've probably already seen in your Ant experience to this point, there are times when the Ant app will encounter an error in the build and halt the process. We can do the same things using the BuildException exception. Here is a more fully defined class:

public class NewTask extends{
 public void execute() throws BuildException {
 try {
 // something
 } catch (Exception e) {
 throw new BuildException(e)

If there are any issues with the task, the BuildException exception is thrown and Ant terminates the build. This is all of the code that we need to use the use the new task. Here's an example build script:

<taskdef classname=""

Of course, the task won't do anything, but Ant will do the necessary work of launching the task.