Apache Ant/屬性
外觀
Ant 不像大多數標準程式語言那樣擁有變數。Ant 擁有一個稱為 **屬性** 的結構。瞭解屬性的工作原理對於理解 Ant 如何(以及為何)如此有效至關重要。
以下是一個關於如何設定和使用屬性的簡單演示
<project name="My Project" default="MyTarget">
<!-- set global properties -->
<property name="SrcDir" value="src"/>
<property name="BuildDir" value="build"/>
<target name="MyTarget">
<echo message = "Source directory is = ${SrcDir}"/>
<echo message = "Build directory is ${BuildDir}"/>
</target>
</project>
請注意,要使用屬性,您必須在它之前放置一個美元符號和左花括號,在它之後放置一個右花括號。不要將它們與括號混淆。
當您執行此程式碼時,您應該得到以下結果
Buildfile: C:\AntClass\PropertiesLab\build.xml
MyTarget:
[echo] Source directory is = src
[echo] Build directory is build
BUILD SUCCESSFUL
Total time: 204 milliseconds
Ant 屬性是 **不可變的**,這意味著一旦它們被設定,它們就不能在構建過程中被更改!這在開始時可能看起來有些奇怪,但這是構建目標一旦編寫後,它們往往會一致地執行而沒有副作用的核心原因之一。這是因為目標只有在必須時才會執行,而您無法預測目標執行的順序。
屬性不必僅在目標內部使用。它們可以在構建檔案的任何地方(或外部屬性檔案)設定,並在設定後在構建檔案的任何地方引用。
以下是一個小型 Ant 專案,演示了屬性的不可變性
<project name="My Project" default="MyTarget">
<target name="MyTarget">
<property name="MyProperty" value="One"/>
<!-- check to see that the property gets set -->
<echo>MyProperty = ${MyProperty}</echo>
<!-- now try to change it to a new value -->
<property name="MyProperty" value="Two"/>
<echo>MyProperty = ${MyProperty}</echo>
</target>
</project>
當您執行此程式碼時,您應該得到以下輸出
Buildfile: C:\AntClass\PropertiesLab\build.xml
MyTarget:
[echo] MyProperty = One
[echo] MyProperty = One
BUILD SUCCESSFUL
Total time: 343 milliseconds
請注意,儘管嘗試將 MyProperty 更改為 "Two",但 MyProperty 的值 **並沒有** 改變。Ant **不會** 警告您此事。
對於新手來說,這可能看起來很奇怪,但這非常適合構建複雜的樹形值,這些值一旦設定就可以反覆使用。它使您的構建指令碼易於維護和可靠。
Ant 還有一套不錯的 "內建" 屬性,您可以使用它們
這演示瞭如何讀取系統屬性
<project name="MyProject" default="Display-Builtins">
<target name="Display-Builtins" description="Display Builtin Properties">
<!-- the absolute path to the location of the buildfile -->
<echo>${basedir}</echo>
<!-- the absolute path of the buildfile -->
<echo>${ant.file}</echo>
<!-- ant.version - the version of Ant that you are running -->
<echo>${ant.version}</echo>
<!-- ant.project.name - the name of the project that is currently executing; it is set in the name attribute of <project>. -->
<echo>${ant.project.name}</echo>
<!-- ant.java.version - the JVM version Ant detected; currently it can hold the values "1.1", "1.2", "1.3", "1.4" and "1.5". -->
<echo>${ant.java.version}</echo>
</target>
</project>
當您執行此程式時,您應該得到類似於以下的輸出
Buildfile: C:\eclipse\workspace\Ant Examples\build.xml
Display-Builtins:
[echo] C:\AntClass\PropertiesLab
[echo] C:\AntClass\PropertiesLab\build.xml
[echo] Apache Ant version 1.6.2 compiled on July 16, 2004
[echo] MyProject
[echo] 1.5
BUILD SUCCESSFUL
Total time: 188 milliseconds
有關內建 Ant 和 Java 屬性的完整列表,請參閱 Ant 參考手冊,或者您可以嘗試以下連結以獲取 Java 屬性:getProperties