JavaRanch Home    
This page:         last edited 01 April 2012         What's Changed?         Edit

Ant Task   

This example shows how to write a simple Ant task. It demonstrates how to access the Project object -the equivalent to the currently executing build file-, and the Target object that called the task. It also accesses data from the build file, both in the form of a property ("name") and a task parameter ("myArg").

See for more elaborate examples and explanations.


public class MyTask extends Task {

    private String myArg;
    private Project proj;
    private Target target;

    // called to initialize the task
    public void init() throws BuildException {
        proj = getProject();
        target = getOwningTarget();
        proj.log("MyTask init");

    // called to execute the task
    public void execute() throws BuildException {
        log("target name: " + target.getName());
        log("value of property 'name' = " + proj.getProperty("name"));
        log("task name: " + getTaskName());
        log("value of task parameter 'myArg' = " + myArg);

    // called to set task parameters; in this case "myArg"
    public void setMyArg (String _myArg) {
        this.myArg = _myArg;

It would be invoked like this:

<property name="name" value="myPropertyValue" />

<taskdef name="MyTaskName" classname="MyTask" />

<target name="myTarget">
    <echo message="before MyTask"/>
    <MyTaskName myArg="myArgValue" />
    <echo message="after MyTask"/>

CategoryCodeSamples CodeBarn BuildToolsFaq

JavaRanchContact us — Copyright © 1998-2014 Paul Wheaton