继承Task类
这里需要实现excute方法,我们在这里调用函数,而不是在构造函数中(回返回null)。
import org.apache.tools.ant.Task;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
public class HelloWorld extends Task {
//get message from the ant Project
String msg;
public void setMessage(String msg) {
this.msg = msg;
}
public void execute() {
if (msg==null) {
throw new BuildException("no message received");
}
System.out.println("receive msg:"+msg);
//get the name of Ant Project
String projectName = getProject().getProperty("ant.project.name");
System.out.println("The name of Project :"+projectName);
}
}
生成jar
下面需要将上述的Java文件编译并打包成jar。
执行ant -f generate-jar.xml
。
<?xml version="1.0" encoding="ISO-8859-1"?>
<project name="MyTask" basedir="." default="jar">
<property name="src.dir" value="src"/>
<property name="classes.dir" value="classes"/>
<target name="clean" description="Delete all generated files">
<delete dir="${classes.dir}" failonerror="false"/>
<delete file="${ant.project.name}.jar"/>
</target>
<target name="compile" description="Compiles the Task">
<mkdir dir="${classes.dir}"/>
<javac srcdir="${src.dir}" destdir="${classes.dir}"/>
</target>
<target name="jar" description="JARs the Task" depends="compile">
<jar destfile="${ant.project.name}.jar" basedir="${classes.dir}"/>
</target>
</project>
执行Task任务
这里首先需要定义Task,然后执行。
<?xml version="1.0" encoding="ISO-8859-1"?>
<project name="MyTask" basedir="." default="use">
<taskdef name="helloworld" classname="HelloWorld" classpath="${ant.project.name}.jar"/>
<target name="use" description="Use the Task">
<helloworld message="Hi,This is MyTask!!!"/>
</target>
</project>
结果如图:
嵌套元素
- 创建Message内部类,来收集嵌套元素应当包含的信息。
public class Message {
public Message() {}
String msg;
public void setMsg(String msg) { this.msg = msg; }
public String getMsg() { return msg; }
}
- 以List方式保持Message对象
Vector messages = new Vector();
- 实例化Message对象,保存List上面的引用,并返回给Ant
public Message createMessage() {
Message msg = new Message();
messages.add(msg);
return msg;
}
- 在excute方法中遍历该list
public void execute() {
if (message!=null) log(message);
for (Iterator it=messages.iterator(); it.hasNext(); ) {
Message msg = (Message)it.next();
log(msg.getMsg());
}
}
- 下面在build.xml中使用嵌套元素
<taskdef name="Nested-helloworld" classname="NestedElements" classpath="${ant.project.name}.jar"/>
<!-- 嵌套-->
<Nested-helloworld>
<message msg="Nested Element 1"/>
<message msg="Nested Element 2"/>
</Nested-helloworld>