|
12.1. Creating a Simple Custom Ant TaskCreating new Ant tasks is simple since all you need is an execute( ) method. Example 12-1 is a Java class named Greeting that displays the text "No worries.". Example 12-1. A simple Ant task (ch12/greetingtask/src/Greeting java)public class Greeting { public void execute( ) { System.out.println("No worries."); } } To install this class as a new Ant task, you compile this code and use the taskdef task to declare it in Ant. The attributes of the taskdef task are shown in Table 12-1.
The taskdef task's classpath attribute is a path-like structure and can be set with a nested classpath element. The build file in Example 12-2 builds the simple Ant task and JARs it in greeting.jar. The taskdef task in the same build file retrieves the task from that JARfile and executes the task, which should print out the "No worries." message. Example 12-2. Build file for a simple Ant task (ch12/greetingtask/build.xml)<?xml version="1.0"?> <project default="main"> <property name="src" location="src"/> <property name="output" location="output"/> <target name="main" depends="jar"> <taskdef name="greeting" classname="Greeting" classpath="greeting.jar"/> <greeting/> </target> <target name="jar" depends="compile"> <jar destfile="greeting.jar" basedir="${output}"/> </target> <target name="compile"> <mkdir dir="${output}"/> <javac srcdir="${src}" destdir="${output}"/> </target> </project> Here's what you see when the build file runs. The execute( ) method of the task's code was indeed called, displaying the expected message: %ant Buildfile: build.xml compile: [mkdir] Created dir: /home/steven/ant/ch12/greetingtask/output [javac] Compiling 2 source files to /home/steven/ant/ch12/greetingtask/output jar: [jar] Building jar: /home/steven/ant/ch12/greetingtask/greeting.jar main: [greeting] No worries. BUILD SUCCESSFUL Total time: 3 seconds |
|