Home > Tech Tips > How to create a jar file using Ant that refers to other jar files?

How to create a jar file using Ant that refers to other jar files?

September 29th, 2006 Leave a comment Go to comments

To create a jar file named “TestWizard.jar” that uses at least 10 other jar files in a folder named “lib”. Build file should be created in such a way that build.xml doesn’t need to be modified when a new jar file is added to the lib folder.

To execute TestWizard.jar, that refers to classes residing in the lib folder. All the jars need to be set to the CLASSPATH to that it be visible from TestWizard.jar

Working Solution
Set the Class-Path attribute of MANIFEST.MF inside TestWizard.jar with all the jar files in the library.

Folder structure

lib —
– a.jar
– b.jar
– c.jar

Manifest Classpath setting for TestWizard.jar
<attribute name=”Class-Path” value=”lib/a.jar lib/b.jar lib/c.jar”/>

Code Snippet

<!– Add all the jar files in lib folder to the class path –>
<path id=”build.classpath”>
<fileset dir=”${basedir}/”>
<include name=”lib/*.jar”/>

<pathconvert property=”test.project.manifest.classpath” pathsep=” “>
<path refid=”build.classpath”/>
<globmapper from=”*.jar” to=”lib/*.jar”/>

<!– Create jar file –>
<target depends=”compile” name=”jar”>
<jar jarfile=”${basedir}/${TestWizard.jar}”>
<fileset dir=”${build}” />
<attribute name=”Main-Class” value=”com.test.panels.TestMain”/>
<attribute name=”Class-Path” value=”${test.project.manifest.classpath}”/>


Erroneous Approaches

  • If you just include the external jar files (from lib folder) into TestWizard.jar, then the classpaths won’t be set correctly. Alternative is use onejar solution (http://one-jar.sourceforge.net/)
  • Create a batch file, that will set the set the classpath individually to all the jar files in the lib folder and then execute TestWizard.jar. This might work, but I was experiencing classnotfound exceptions

Categories: Tech Tips Tags:
  1. Tim
    September 6th, 2007 at 17:48 | #1

    This was bugging me like crazy – thanks for posting this!!

  2. Jeevan
    September 12th, 2007 at 06:08 | #2

    Thanks, however returns a value with the complete path (on Windows, D:\xxx\yyy\…) which is not wanted in a Manifest file – can it not return relative paths?

  3. Jeevan
    September 12th, 2007 at 06:12 | #3

    Discovered it.
    To make relative paths use the embedded task

  4. N.Krishna Sumanth
    December 30th, 2008 at 02:29 | #4

    Very much helpful

    thanks & regards

  5. Venkat
    October 15th, 2009 at 14:17 | #5

    Awesome!!! It’s working perfect!. Thanks a lot

  6. October 31st, 2010 at 00:02 | #6
  1. July 17th, 2011 at 00:04 | #1