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

定义 target
使用 `
例如:
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` 控制










