Ant compiling - How to reference the jar files in your lib directory during your Ant compile process

Here’s a quick snippet of code from an Ant build script that demonstrates how to create a classpath variable in an Ant script, where the classpath is built from all of the jar files in your project’s lib folder:

<path id="build.classpath">
  <fileset dir="lib">
    <include name="**/*.jar"/>
    <include name="**/*.zip"/>
  </fileset>
</path>

As you can see, this section of code creates a variable named build.classpath, and this variable contains a list of all the jar files from the lib folder. Once you create a variable like this, you can use it to represent your classpath during a later compile task, which I'll demonstrate shortly.

Handling jar files in subdirectories

Before I get into the compile task, I want to note that another nice thing this syntax does is include jar files that are in subdirectories of your lib directory in the classpath. The special */ syntax tells Ant to look in subdirectories. I like this, because then I can keep all my Apache jar files in one subdirectory, and my database jar files in another subdirectory, and other jar files like JUnit and Cobertura in another subdirectory, etc.

Using the classpath when compiling

Once you've created a classpath variable as shown above, compiling your Java application from your Ant build script is straightforward. Just create a compile target that invokes the javac task, and give the javac task the classpath variable you created earlier, in my case build.classpath.

<target name="compile" depends="clean">
  <javac destdir="classes" source="1.5" >
    <src path="src"/>
    <classpath refid="build.classpath"/>
  </javac>
</target>

This compile target compiles all the files found in the src directory, using the classpath we created, and puts the output, compiled files in the classes directory.