Ant - 自定义组件
Ant 允许非常轻松地创建和使用自定义组件。 可以通过实现 Condition、Selector、Filter 等接口来创建自定义组件。 一旦一个类准备好了,我们就可以使用 typedef 在 build.xml 中创建组件,以便在任何目标下使用。
语法
首先将一个类定义为 Ant 自定义组件,例如 TextSelector.java,然后在 build.xml 中定义一个选择器。
<typedef name="text-selector" classname="TextSelector" classpath="."/>
Then use that component within a target.
<target name="copy">
<copy todir="${dest.dir}" filtering="true">
<fileset dir="${src.dir}">
<text-selector/>
</fileset>
</copy>
</target>
示例
使用以下内容创建 TextSelector.java 并将其放在与 build.xml 相同的位置 −
import java.io.File;
import org.apache.tools.ant.types.selectors.FileSelector;
public class TextFilter implements FileSelector {
public boolean isSelected(File b, String filename, File f) {
return filename.toLowerCase().endsWith(".txt");
}
}
在 src 目录中创建一个 text1.txt 和一个 text2.java。 目标是仅将 .txt 文件复制到构建目录。
使用以下内容创建 build.xml −
<?xml version="1.0"?>
<project name="sample" basedir="." default="copy">
<property name="src.dir" value="src"/>
<property name="dest.dir" value="build"/>
<typedef name="text-selector" classname="TextSelector" classpath="."/>
<target name="copy">
<copy todir="${dest.dir}" filtering="true">
<fileset dir="${src.dir}">
<text-selector/>
</fileset>
</copy>
</target>
</project>
输出
在上述构建文件上运行 Ant 会产生以下输出 −
F:\tutorialspoint\ant>ant Buildfile: F:\tutorialspoint\ant\build.xml copy: [copy] Copying 1 file to F:\tutorialspoint\ant\build BUILD SUCCESSFUL Total time: 0 seconds
现在只复制 .txt 文件。

