Ant - 自定義元件



Ant 允許輕鬆地建立和使用自定義元件。可以透過實現 Condition、Selector、Filter 等介面來建立自定義元件。一旦類準備好,便可以使用typedef在 build.xml 中建立元件,供任何目標使用。

句法

首先定義一個類作為 Ant 自定義元件,例如 TextSelector.java,然後在 build.xml 中定義一個選擇器。

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

示例

使用以下內容建立 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 檔案。

廣告