It is likely that many tasks within a project will need identical configuration values. Ant provides the means to define such values in global variables rather than requiring the developer to duplicate them in many places throughout a file.
Many definitions can be made global by placing the definition at the top level of the file and adding an identifier. The fileset definition that obtains all Java files could be made global and used by the ls task as follows:
<fileset dir="." id="defaultFiles"> <include name="**/*.java"/> </fileset> <target name="fileList"> <ls> <fileset refid="defaultFiles"/> </ls> </target>
The global fileset definition looks like any of the nested definitions seen so far, but it adds an id, which here is defaultFiles. There is nothing special about this name, and any legal identifier can be used. The target then uses this fileset tHRough the refid attribute within its nested fileset.
A fileset initially constructed by referencing a global fileset can be further manipulated by nesting any of the elements examined previously. A target that operates only on handwritten files could filter defaultFiles as
<fileset refid="defaultFiles"> <exclude name="**/autogen/*.java"/> </fileset>
It is even possible for global filesets to reference and modify other filesets. This ability leads to a common technique where one global fileset will define a base set of files and directories, and subsequent definitions and targets will modify this set as needed. For example, a compile target might use defaultFiles as is, and a target that generates documentation might use the fileset with autogenerated files removed.
Errors to Watch ForGlobal variables cannot be redefined. The first definition that Ant encounters will be used throughout the project. |