AntCall Task:執行過程中呼叫並執行其他target
AntCall 任務的作用是允許在一個target的執行過程中呼叫並執行其他的target。例如,在打包專案前需要對專案進行編譯,那麼可以在打包專案的target中通過AntCall任務使得編譯的target先執行。當然這種情況也可以通過target間設定depends屬性來實現。AntCall任務必須在target元素內執行,這個任務不能在target元素外執行。
4.2.1 AntCall Task屬性及功能
AntCall 任務主要包括target,inheritAll和inheritRefs 3個屬性,具體說明如下:
(1)target屬性:在AntCall任務中target屬性的作用是指定要被呼叫執行的target,通過名稱指定這個target屬性是必需的。值得注意的是,當通過AntCall任務呼叫的target存在依賴的target(depends中指定了target),則depends屬性中被指定的target也會被執行。
(2)inheritAll屬性:用於指定是否繼承當前的屬性。預設時為true,代表被呼叫的target可使用這些屬性。
(3)inheritRefs屬性:用於指定是否覆蓋reference屬性或者是否建立一個對當前reference屬性的引用。在預設的情況下,AntCall任務不會覆蓋reference屬性,除非把inheritRefs屬性設為true。預設時inheritRefs屬性為false。
4.2.2 利用AntCall Task實現target間呼叫的例項
利用AntCall任務來實現target間的相互呼叫。下面編寫構件檔案antcallSample.xml,實現在targetA中呼叫執行targetB。構件檔案內容如下:
<?xml version="1.0"?>
<project name="antcallSample" default="targetA">
<target name="targetA">
<echo message="In targetA calling targetB"/>
<!-- //呼叫targetB -->
<antcall target="targetB" >
</antcall>
<echo message="After call targetB" />
</target>
<target name="targetB" >
<echo message="In targetB" />
</target>
</project>
儲存構件檔案,然後在命令列執行命令ant –f antcallSample.xml,執行結果如圖4.3 所示。
圖4.3 antcallSample.xml
上面的例子的作用是在執行targetA的過程中執行targetB。如果targetB中設定了depends屬性,則depends屬性中指定的target也會被執行。修改antcallSample.xml如下,以演示depends的依賴關係:
<?xml version="1.0"?>
<project name="antcallSample" default="targetA">
<target name="init" >
<echo message="In init target"/>
</target>
<target name="targetA">
<echo message="In targetA calling targetB"/>
<antcall target="targetB" >
</antcall>
<echo message="After call targetB" />
</target>
<target name="targetB" depends="init">
<echo message="In targetB" />
</target>
</project>
儲存構件檔案,然後再次執行ant –f antcallSample.xml命令,執行結果如圖4.4所示。
圖4.4 antcallSample.xml命令的執行結果
上面的執行結果表明:在執行targetA時呼叫targetB,由於targetB依賴於init target。因此init target先於targetB執行。
4.2.3 利用AntCall Task實現target間呼叫時傳遞引數的例項
當需要從一個target傳遞引數到被呼叫的target時,可以使用<param> 型別進行傳遞。當然也可以在target中定義property來實現,與Java中的方法呼叫時傳遞引數相似。修改antcallSample.xml以實現傳遞引數的功能,內容如下:
<?xml version="1.0"?>
<project name="antcallSample" default="targetA">
<target name="init" >
<echo message="In init target"/>
</target>
<target name="targetA">
<echo message="In targetA calling targetB"/>
<!-- //通過property傳遞 -->
<property name="prop" value="prop property" />
<antcall target="targetB" >
<!-- // 通過antcall設定param實現 -->
<param name="path1" value="path1 param" />
</antcall>
<echo message="After call targetB" />
</target>
<target name="targetB" depends="init">
<echo message="In targetB" />
<echo message="path1=${path1}" />
<echo message="prop=${prop}" />
</target>
</project>
再次執行ant –f antcallSample.xml命令,執行結果如圖4.5所示。
圖4.5 antcallSample.xml
從執行結果可看出,通過property指定和通過AntCall中的param指定的屬性都傳遞到targetB中。對於param 型別只有兩個屬性:name和value。由於AntCall任務中的inheritAll屬性預設時為true,所以property能被targetB引用。如果targetB中也定義了相同的property,那麼可以通過設定inheritRefs屬性和reference型別進行覆蓋。