Ant if和unless都是<target>元素(tasks)的屬性。 這些屬性用于控制任務(wù)是否運行的任務(wù)。
除了target之外,它還可以與<junit>元素一起使用。
在早期版本和Ant 1.7.1中,這些屬性僅是屬性名稱。 如果定義了屬性,則即使值為false也會運行。
例如,即使在傳遞false之后也無法停止執(zhí)行。
文件:build.xml -
<project name="java-ant project" default="run">
<target name="compile">
<available property="file.exists" file="some-file"/>
<echo>File is compiled</echo>
</target>
<target name="run" depends="compile" if="file.exists">
<echo>File is executed</echo>
</target>
</project>
輸出:
無參數(shù):沒有命令行參數(shù)運行它。 只需輸入ant到終端,但首先找到項目位置,它將顯示空輸出。

使用參數(shù):現(xiàn)在只傳遞參數(shù):false。
Ant -Dfile.exists = false
得到以下結(jié)果:
E:\worksp\ant\AntProject>Ant -Dfile.exists = false
Buildfile: E:\worksp\ant\AntProject\build.xml
compile:
[echo] File is compiled
run:
[echo] File is executed
BUILD SUCCESSFUL
Total time: 0 seconds
使用參數(shù):現(xiàn)在只傳遞參數(shù):true。
Ant -Dfile.exists = true
執(zhí)行上面示例代碼,得到以下結(jié)果:
E:\worksp\ant\AntProject>Ant -Dfile.exists = true
Buildfile: E:\worksp\ant\AntProject\build.xml
compile:
[echo] File is compiled
run:
[echo] File is executed
BUILD SUCCESSFUL
Total time: 0 seconds
從Ant 1.8.0開始,可以使用屬性擴展,只有當(dāng)value為true時才允許執(zhí)行。在新版本中,它提供了更大的靈活性,現(xiàn)在可以從命令行覆蓋條件值。請參閱下面的示例。
文件:build.xml
<project name="java-ant project" default="run">
<target name="compile" unless="file.exists">
<available property="file.exists" file="some-file"/>
</target>
<target name="run" depends="compile" if="${file.exists}">
<echo>File is executed</echo>
</target>
</project>
輸出
無參數(shù):在沒有命令行參數(shù)的情況下運行它。 只需輸入ant到終端,但首先找到項目的位置,它將顯示空輸出。
使用參數(shù):現(xiàn)在傳遞參數(shù),但只使用false。
Ant -Dfile.exists = false
沒有輸出,因為這次沒有執(zhí)行。
使用參數(shù):現(xiàn)在傳遞參數(shù),但只使用true。 現(xiàn)在它顯示輸出,因為if被評估。
Ant -Dfile.exists = true
E:\worksp\ant\AntProject>Ant -Dfile.exists = true
Buildfile: E:\worksp\ant\AntProject\build.xml
compile:
run:
[echo] File is executed
BUILD SUCCESSFUL
Total time: 0 seconds