target 是 Ant 构建脚本的基本执行单元,用于封装编译、打包等任务;通过 定义,需指定 name,可设 depends(自动先执行依赖)、description(ant -projecthelp 显示)、if/unless(条件执行);默认执行第一个 target,命令行可指定如 ant compile 或 ant clean jar。

在 Ant 的 `build.xml` 中,`target` 是构建过程的基本执行单元,用来封装一组相关任务(如编译、打包、清理等)。定义和调用 target 是 Ant 构建脚本的核心。
定义 target
使用 `` 元素定义一个 target,必须指定 `name` 属性,还可选设置 `depends`(依赖其他 target)、`description`(描述用途)、`if` 或 `unless`(条件执行)等属性。
例如:
javac srcdir="src" destdir="build/classes"/>
说明:
- `name` 是必需的,用于唯一标识该 target
- `depends` 中列出的 target 会**自动先执行**(支持多个,用逗号分隔,如 `depends="clean,init"`)
- `description` 不影响执行,但运行 `ant -projecthelp` 时会显示,便于团队理解
- `if="property.name"` 表示仅当该 property 已定义且非空时才执行;`unless="prop"` 则相反
调用 target
Ant 默认执行 `build.xml` 中**第一个定义的 target**(除非显式指定)。
命令行中调用方式:
-
`ant` —— 执行默认 target(即第一个 target)
-
`ant compile` —— 执行名为 `compile` 的 target(及其依赖)
-
`ant clean jar` —— 依次执行 `clean` 和 `jar`(注意:不是并行,也不自动处理跨 target 依赖,除非 `jar` 自己声明 `depends="clean,compile"`)
-
`ant -projecthelp` —— 列出所有带 `description` 的 target 及说明
常见注意事项
几个容易忽略但关键的点:
- target 名称不能包含空格或特殊字符(推荐用小写字母+点/下划线,如 `test-unit`)
- 依赖关系是**静态解析**的:Ant 先扫描全部 target,构建执行顺序图,再运行;不会重复执行同一 target(即使被多个 target 依赖)
- 没有“参数传递”机制:target 之间不能直接传参,需通过 `` 配合 `if`/`unless` 控制行为,或用 ``(不推荐,已过时)
- 想让某个 target **只运行一次且不被默认触发**?可加 `depends=""` 并避免放在最前面,或用 `unless` 控制
基本上就这些。定义清晰、依赖合理、命名规范,就能写出可维护的 Ant 构建脚本。
以上就是Ant的build.xml中怎么定义和调用target的详细内容,更多请关注php中文网其它相关文章!