Ant 简明教程

Ant - Custom Components

Ant 允许轻松创建和使用自定义组件。可通过实现 Condition、Selector、Filter 等接口来创建自定义组件。一旦类准备就绪,我们便可以使用 typedef 在 build.xml 内创建该组件,以便在任何目标下使用。

Ant allows to create and use custom components very easily. Custom Components can be created by implementing Condition, Selector, Filter etc. interfaces. Once a class is ready, we can use typedef to create the component within build.xml to be used under any target.

Syntax

首先,将一个类定义为 Ant 自定义组件,比如 TextSelector.java,然后在 build.xml 中定义一个选择器。

First define a class as Ant custom component say TextSelector.java then in build.xml, define a selector.

<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>

Example

使用以下内容创建 TextSelector.java,将其放置在与 build.xml 相同的位置 −

Create TextSelector.java with the following content and put the same in same place as 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 文件复制到构建目录。

Create a text1.txt and a text2.java in src directory. Target is to be copy only .txt file to build directory.

使用以下内容创建 build.xml −

Create build.xml with the following content −

<?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>

Output

在上述构建文件上运行 Ant 会生成以下输出:

Running Ant on the above build file produces the following output −

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 文件。

Now only .txt file is copied.