編寫自訂任務,輕鬆擴充Ant

來源:互聯網
上載者:User
Ant內建了大量的任務(Task),在網上也有大量的任務可用,可是如果你面對的是別人根本不會想到的問題,怎麼辦呢?其實,只要花一點點功夫就可以編寫出自己的任務出來。我開始也沒想到會這樣簡單(做嵌套任務碰到一點問題),由此可見Ant的結構設計是相當優秀的。   假設我們需要顯示任務執行各花了多少時間,寫一個TimerTask   起步:覆蓋org.apache.tools.ant.Task 的execute 方法   import org.apache.tools.ant.Task; import org.apache.tools.ant.BuildException;     public class TimerTask extends Task { public void execute() throws BuildException {     System.out.println("I am a timer"); } } 注意,編譯時間ant.jar必須在Classpath上。 簡單起見,假設java源檔案,類檔案在同一目錄下,在此目錄再寫一個build.xml檔案: <?xml version="1.0" ?> <project name="testTimer" default="test" basedir="."> <taskdef name="timer" classname="TimerTask" classpath="."/>   <target name="test">     <timer /> </target> </project>   開啟Dos視窗,到此目錄,運行ant 夠簡單吧!如果類路徑比這複雜或者在jar檔案中,設定<taskdef>的classpath屬性就行了。   繼續:設定屬性 假設我們想添加一個action屬性,在Java檔案中: private String action; …. public void execute() throws BuildException { if (action.equals(“init”)) {         … } … }   public String getAction() { return action; }   public void setAction(String string) { action = string; }   在xml檔案中: <timer action=”init” />   使用Project 儲存中間結果 對於這個任務來講,必須把時間值儲存起來,比較合適的就是org.apache.tools.ant.Project了,Project對象生命期是整個Build,並且可以通過setProperty, getProperty等方法儲存/擷取值。   public void execute() throws BuildException {     if (getOwningTarget() == null)         return;     Project proj = getOwningTarget().getProject();     …     // can do smt with proj now }   晉級:嵌套任務 如果我們想要在Timer下面再嵌套子任務(好像沒有這個必要 :-): <timer action=”init” > <foo /> </timer>   那我們首先只需要寫一個簡單的FooTask,然後在build.xml加上<foo>的定義: <taskdef name="timer" classname="TimerTask" classpath="."/> <taskdef name="foo" classname="FooTask" classpath="."/>    然後給TimerTask添加一個方法: public void addFoo(FooTask foo) { } 注意:addXXX的XXX由<taskdef>中的name決定,Ant會利用Java Reflection去找;類型必須是具體的類型FooTask,不能是Task。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.