Java – ant, jar files, and Class-Path oh the

antjarjava

I am trying to rearchitect my build technique for creating Java jar files which depend on common 3rd party jar files. (GlazedLists, Apache Commons, etc.)

I had been chucking them all into {Java JRE dir}/lib/ext so they would automatically be seen by the JRE, but that led to problems like not remembering that I need to distribute certain jar files, so I'd like to learn to be more explicit.

So I moved them all into c:\appl\java\common\, added them to the Eclipse build path, aand defined this in my ant file:

<path id="javac_classpath">
    <fileset dir="${libDir}">
        <include name="*.jar"/>
    </fileset>
    <fileset dir="c:/appl/java/common">
        <include name="*.jar"/>
    </fileset>
</path>

I have my Class-Path manifest header set to "." in my jar task but that doesn't seem to work even if I put the relevant jar files into the same directory as my application jar file. I can add them all manually one-by-one to the Class-Path header, but I'm wondering, is there an easier way to get the Class-Path header setup properly?

Best Solution

This is all you need:

<path id="build-classpath">
    <fileset dir="${dist}/lib">
        <include name="*.jar"/>
    </fileset>
</path>
<manifestclasspath property="lib.list" jarfile="${dist}/lib/myprog.jar">
    <classpath refid="build-classpath"/>
</manifestclasspath>
<jar jarfile="${dist}/lib/myprog.jar"
     basedir="${build}"
     includes="com/my/prog/**" >
    <manifest>
        <attribute name="Main-Class" value="com.my.prog.MyProg"/>
        <attribute name="Class-Path" value="${lib.list}"/>
    </manifest>
</jar>

As you can probably see, it assumes you've compiled your Java classes and output them to ${build}. It also assumes you've copied your jarfiles to ${dist}/lib.

That said, it would be worth looking into other build systems which have built-in support for dependencies, such as Maven and Gradle. These other build systems have already thought through many common project structures and build operations, so you don't have to script everything down to the last detail.