javac
要在编译任务中仅包含文件夹中的特定文件,请使用<include>
元素指定文件。当<include>
指定一个元素时,只有命名文件(及其项目依赖项)将包含在编译中。
示例项目
项目目录: /home/project
源目录: /home/project/src
构建目录: /home/project/build
build.xml(位于 /home/project 中)
<?xml version="1.0" encoding="UTF-8"?>
<project name="compile_test" basedir="." default="compile_class1">
<property name="src.dir" value="${basedir}/src" />
<property name="build.dir" location="${basedir}/build" />
<property name="classes.dir" location="${build.dir}/classes" />
<target name="init" description="Initialize the build directory.">
<mkdir dir="${build.dir}" />
<mkdir dir="${classes.dir}" />
</target>
<target name="clean" description="Delete all files created by this script.">
<delete dir="${build.dir}" />
</target>
<target name="compile_class1" depends="init">
<javac srcdir="${src.dir}" destdir="${classes.dir}"
includeantruntime="false">
<include name="com/mypackage/Class1.java" />
</javac>
</target>
<target name="compile_class2" depends="init">
<javac srcdir="${src.dir}" destdir="${classes.dir}"
includeantruntime="false">
<include name="com/mypackage/Class2.java" />
</javac>
</target>
</project>
Java 源文件
Class1.java
package com.mypackage;
public class Class1 {
public static void main(String[] args){
System.out.println("Class1");
}
}
Class2.java
package com.mypackage;
public class Class2 {
public static void main(String[] args){
Class3 class3 = new Class3();
System.out.println(class3.getMessage());
}
}
Class3.java
package com.mypackage;
public class Class3 {
public String getMessage() {
return "The answer is 42.";
}
}
蚂蚁输出
Ant 目标 compile_class1
$ ant clean compile_class1
Buildfile: /home/project/build.xml
clean:
[delete] Deleting directory /home/project/build
init:
[mkdir] Created dir: /home/project/build
[mkdir] Created dir: /home/project/build/classes
compile_class1:
[javac] Compiling 1 source file to /home/project/build/classes
BUILD SUCCESSFUL
Total time: 1 second
请注意,虽然有三个 Java 源文件,但只有<include>
元素指定的文件被编译。
Ant 目标 compile_class2
$ ant clean compile_class2
Buildfile: /home/project/build.xml
clean:
[delete] Deleting directory /home/project/build
init:
[mkdir] Created dir: /home/project/build
[mkdir] Created dir: /home/project/build/classes
compile_class2:
[javac] Compiling 1 source file to /home/project/build/classes
BUILD SUCCESSFUL
Total time: 1 second
在这种情况下,虽然 Ant 目标compile_class2
只在嵌套<include>
元素中指定了一个文件,但 Class2.java 和 Class3.java 都被编译了,因为 Class2.java 依赖于 Class3.java。如果编译时没有包含 Class2.java 的依赖项,那么在尝试执行 Class2 时,会收到无法定位 com.mypackage.Class3 的错误。