Monday, September 02, 2013

Creating a Manifest File with Ant - Class not found when creating Jars

When creating a jar file you create a manifest file to specify the main class that should execute when the jar is executed. You also specify the class path for the jar. If using Ant you can create the jar file and the manifest at the same time.

If you are getting class not found errors perhaps you haven't added the class path to the manifest file in your jar.

To create a jar using ant use the jar task:

https://ant.apache.org/manual/Tasks/jar.html

Create a manifest file automatically using manifest task as follows:

http://ant.apache.org/manual/Tasks/manifest.html

        <manifest>
            <attribute name="Main-Class" value="com.radicalsoftware.Main"/>
            <attribute name="Class-Path"
                            value="lib/some-class-1.0.jar lib/some-other-class-1.0.jar lib/xerces.jar"/>
        </manifest>

So you might have an ant target that ends up looking something like this where you have defined your variables in a properties file (the items below starting with $ in curly brackets {} will be replaced with values defined in your script earlier.

    <target name="jar" depends="compile">
        <echo message="****************/*.*"/>
        <echo message="creating ${dir.dist}\radicalsoftware.jar"/>
        <echo message="****************/*.*"/>
        <jar destfile="${dir.dist}/${ant.project.name}.jar">
        <fileset dir="${dir.compiled}" />
        <exclude name=".classpath"/>
        <exclude name=".project"/>
        <exclude name="bin/**/*.*"/>
        <zipfileset file="${dir.src}${project.src}\javax\servlet\LocalStrings.properties"
        fullpath="javax\servlet\LocalStrings.properties"/>
        <zipfileset file="${dir.src}${project.src}\resources\com\radicalsoftware\mime.properties"
        fullpath="com\radicalsoftware\mime.properties"/>
        <zipfileset file="${dir.src}${project.src}\resources\com\radicalsoftware\encoding.properties"
        fullpath="com\radicalsoftware\encoding.properties"/>
        <manifest>
            <attribute name="Main-Class" value="com.radicalsoftware.Main"/>
            <attribute name="Class-Path"
                            value="lib/some-class-1.0.jar lib/some-other-class-1.0.jar lib/xerces.jar"/>
        </manifest>
        </jar>
    </target>