Kaarel Purde
Kaarel Purde

Reputation: 1265

How to add external jars with ant?

I am trying to figure out how to add external jars with Ant.

I made this simple project with NetBeans that "uses" an external library (gson 2.3.1): Gson

This is how the project looks in filesystem (the Gson jar is in 'lib'): enter image description here

And this is the build.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project name="Project" default="main" basedir=".">

    <property name="lib.dir" location="lib" />
    <property name="src.dir" location="src" />
    <property name="build.dir" location="build" />
    <property name="classes.dir" location="${build.dir}/classes" />
    <property name="jar.dir" location="${build.dir}/jar" />

    <target name="main" depends="execute">
        <echo message="targets completed" />
    </target>

    <target name="execute" depends="jar">
        <java jar="${jar.dir}/${ant.project.name}.jar" fork="true" />
    </target>

    <target name="jar" depends="compile">
        <jar destfile="${jar.dir}/${ant.project.name}.jar" basedir="${classes.dir}">
            <manifest>
                <attribute name="Main-Class" value="project.Project"/>
            </manifest>
        </jar>
    </target>

    <target name="compile" depends="makedir">
        <javac srcdir="${src.dir}" destdir="${classes.dir}">
            <classpath>
                <path>
                    <fileset dir="${lib.dir}">
                        <include name="**/*.jar" />
                    </fileset>
                </path>
            </classpath>
        </javac>
    </target>

    <target name="makedir" depends="clean">
        <mkdir dir="${build.dir}" />
        <mkdir dir="${classes.dir}" />
        <mkdir dir="${jar.dir}" />
    </target>

    <target name="clean">
        <delete dir="${build.dir}" />
    </target>

</project>

If I run this with Ant I get exception [java] Exception in thread "main" java.lang.NoClassDefFoundError: com/google/gson/Gson from 'execute' target. What is wrong?

Upvotes: 0

Views: 2191

Answers (1)

Rahul Yadav
Rahul Yadav

Reputation: 1513

You will need to add following to your jar target

<zipgroupfileset dir="${lib-dir}" includes="**/*.jar"/>

Upvotes: 1

Related Questions