Friday, March 16, 2012

Ant task for compiling classes

The following build.xml file contains 3 targets for deleting unnecessary directories, creating required directories and compiling classes in a specified directory.

//build.xml
  1. <project name="SampleBuildFile" default="compile-classes" basedir=".">
  2.     <property name="src.dir" value="src" />
  3.     <property name="lib.dir" value="lib" />
  4.     <property name="build.loc" value="E:/temp/build" />
  5.     <property name="classes.dir" value="${build.loc}/classes" />
  6.     <!-- Setting ClassPath -->
  7.     <path id="classpath">
  8.         <pathelement location="${classes.dir}"/>
  9.         <fileset dir="${lib.dir}" includes="*.jar"/>
  10.     </path>
  11.     <!-- Delete directories that are not needed -->
  12.     <target name="delete-dir" >
  13.             <delete dir="${build.loc}"/>
  14.             <echo> /* Deleted existing Directories */ </echo>
  15.     </target>
  16.     <!-- Create Directories -->
  17.     <target name="create-dir" depends="delete-dir">
  18.         <mkdir dir="${classes.dir}"/>
  19.         <echo> /* Created Directories */ </echo>
  20.     </target>
  21.     <target name="compile-classes" depends="create-dir">
  22.         <javac destdir="${classes.dir}" includeantruntime="false" debug="true" srcdir="${src.dir}">
  23.             <classpath refid="classpath"/>
  24.         </javac>
  25.         <echo> /* Compiled Classes */ </echo>
  26.     </target>
  27. </project>
In the above build file,

              Property task is used to set a property by name and value which are case sensitive.The attribute 'name' represents name of property and 'value' represents value to the property. By using this we can have an advantage when we want any modification further on property values because value represented by property name is used through out the build file so no need to change the property value for all.

Path task is used to building class path required to execute different ant targets in the build file.

             Here by default the 'compile-classes' target 'll call first when the build file 'll run, but this target depends on 'create-dir' target so it 'll call 'create-dir' target before it run.Again the 'create-dir' depends upon 'delete-dir' so it 'll call the 'delete-dir' target before 'create-dir' run.Clearly, the order of execution 'll be 
                       delete-dir   =>  create-dir   => compile-classes

             In the 3rd target the 'javac' task 'll compile all the java classes that are in the directory specified by 'srcdir' attribute i.e 'src' directory and all the compiles classes 'll be stored in the directory specified by 'destdir' attribute i.e 'E:/temp/build/classes'

The <classpath> is used to specify the PATH references using path tasks 'id' attribute value.

No comments:

Post a Comment