Ant tip: How to dynamically add all your jar files to your classpath

Here's some sample code you can use in your Ant build scripts to add all the jar files in a directory tree (typically your lib directory) to define a classpath for your Ant build/compile task:

<path id="class.path">
  <fileset dir="lib">
    <include name="**/*.jar" />
  </fileset>
</path>

This code defines a variable named class.path and adds every jar file in your lib directory -- and all directories under it (for those times when you want/need to organize your libraries into multiple folders) -- to this variable. You can then use this variable in your Ant compile task, like this:

<target name="compile" depends="prepare">
  <echo>=== COMPILE ===</echo>

  <echo>Compiling ${src.dir} files ...</echo>
  <javac debug="on" srcdir="${src.dir}" destdir="${target.dir.classes}" includes="com/**">
    <classpath refid="class.path" />
  </javac>
</target>

In particular, notice this line in the compile task where I refer to my class.path variable:

<classpath refid="class.path" />

This is the line where I include my custom-defined classpath into the build/compile process.

Share it!

There’s just one person behind this website; if this article was helpful (or interesting), I’d appreciate it if you’d share it. Thanks, Al.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.