Now, to put all this information together, we will programmatically create a project, give it a single target and task, and call execute() on it. Using our task GreetJon from the description of the Task class, we will build a task that can be executed using its own Main() method.
The project file is as follows:
import org.apache.tools.ant.*;
public class ChapterAntProject extends org.apache.tools.ant.Project{
public ChapterAntProject(){
super.init();
}
public static void main(String[] args){
try{
/*
Create the Project object and add the custom Tag
*/
Project proj = new ChapterAntProject();
proj.setName("jonsProject");
GreetJon task = new GreetJon();
proj.addTaskDefinition("jonsTask", task.getClass());
/*
Create the Target Object as a child
of the project and add the Task to
it
*/
Target targ = new Target();
targ.setName("jonsTarget");
targ.addTask(task);
proj.addTarget("jonsTarget",targ);
proj.setDefaultTarget("jonsTarget");
/*
Execute the Target
*/
proj.executeTarget("jonsTarget");
}
catch(Exception e){
e.printStackTrace();
throw new BuildException("An error occurred while building and running your custom task",e);
}
}
}
The task file is as follows:
import org.apache.tools.ant.*;
public class GreetJon extends Task {
public GreetJon(){
;}
public void execute() throws BuildException{
System.out.println("Hello Zach!");
}
}
Running the project from a Java environment will produce output equivalent to the following Ant build.xml file:
<?xml version="1.0"?> <project name="jonsProject" basedir = "." default = "jonsTarget"> <target name="jonsTarget"> <taskdef name="jonsTask" classname="GreetJon"/> </target> </project>
This example is meant to be a simplified launching point from which you can build many custom tasks, projects, and targets to perform specific actions within the Ant framework.