Antタスクを作る。
今さらですが、Antタスクを作ることになりました。
タスククラスの作成
org.apache.tools.ant.Task を継承して作ります。
- execute()にタスク実行時の処理を書きます。
- パラメータを受け取るには、パラメータ名に対応するsetterを定義します。
- 「name」パラメータを受け取る場合、「setName()」を定義しておきます。
- 定義があればAntタスク実行時に属性値が挿入されます。
package ant; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Task; /** * 「こんにちは」タスク * * @version $Revision:$ * @author $Author:$ */ public class HelloTask extends Task { /** * 名前 */ private String name; /** * 実行回数 */ private int count; /** * タスクを実行する。 * @see Task#execute() */ public void execute() throws BuildException { for ( int i = 0; i < count; i++ ) { System.out.println( "hello! " + name ); } } /** * 名前を設定する。 * @param name 名前 */ public final void setName ( String name ) { this.name = name; } /** * 実行回数を設定する。 * @param count 実行回数 */ public final void setCount ( int count ) { this.count = count; } }
build.xml
作成したタスクを実行するbuild.xmlは以下の通りです。
- taskdefで自作のタスクを定義します。
- パラメータでクラス名とクラスのロード先となるクラスパスを指定します。
- 定義が済めば普通に使えます。
<?xml version="1.0" encoding="euc-jp"?> <project name="hello" default="hello" basedir="."> <!-- コンパイル済みタスクの配置パスを指定する --> <path id="lib.path"> <pathelement location="../class" /> </path> <!-- タスクを定義する --> <taskdef name="hello" classname="ant.HelloTask" classpathref="lib.path"/> <target name="hello"> <hello name="world!" count="3" /> </target> </project>
実行
実行してみます。
[xxx@xxxx]$ ant Buildfile: build.xml hello: [hello] hello! world! [hello] hello! world! [hello] hello! world! BUILD SUCCESSFUL Total time: 9 seconds