What classpath do I need for an Ant taskdef?

TestUser picture TestUser · Oct 14, 2010 · Viewed 18.4k times · Source

I'm new to Ant. Can someone please tell me what value to put for the 'classpathref' for taskdef? Will it be the path of the class file? If yes can an example be given because I tried that and its not working for me.

Answer

martin clayton picture martin clayton · Oct 14, 2010

In the taskdef, the classpathref should be a reference to a previously defined path. The path should include a jar archive that holds the class implementing the task, or it should point to the directory in the file system that is the root of the class hierarchy. This would not be the actual directory that holds your class if your class resides in a package.

Here's an example.

MyTask.java:

package com.x.y.z;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Task;

public class MyTask extends Task
{
    // The method executing the task
    public void execute() throws BuildException {
        System.out.println( "MyTask is running" );
    }
}

Note that the package name is com.x.y.z, so when deployed - lets say the classes are put under a directory called classes - we might see the class here in the file system:

$ ls classes/com/x/y/z
MyTask.class

Here's a simple build.xml that uses the task:

<project name="MyProject" basedir=".">

<path id="my.classes">
    <pathelement path="${basedir}/classes" />
</path>
<taskdef name="mytask" classpathref="my.classes" classname="com.x.y.z.MyTask"/>
<mytask />

</project>

Note that the classpathref given points at the classes directory - the root of the class hierarchy.

When run, we get:

$ ant
Buildfile: .../build.xml
   [mytask] MyTask is running

You can do similar using an explicit classpath, rather than a 'classpathref', for example:

<property name="my.classes" value="${basedir}/classes" />
<taskdef name="mytask" classpath="${my.classes}" classname="com.x.y.z.MyTask"/>