Vicky
Vicky

Reputation: 17355

NoClassDefFound error for a jar created using ant build

I have a java project with class having main method in package com.nik.mypackage. Only one library is referenced which is someLib-5.0.2.jar

This library is in lib folder in eclipse and added to the build path.

I am creating executable jar of the application using the below ant script target:

 <property name="src" location="src"/>
 <property name="build" location="build"/>
 <property name="dist"  location="dist"/>

   <target name="init">
      <tstamp/>
      <mkdir dir="${build}"/>
   </target>


 <target name="compile" depends="init"
    description="compile the source " >
       <javac srcdir="${src}" destdir="${build}">
       <classpath>
         <pathelement path="${classpath}"/>
              <pathelement location="lib/someLib-5.0.2.jar"/>
        </classpath>
       </javac>
   </target>

<target name="dist" depends="compile" description="generate the distribution" >
   <!-- Create the distribution directory -->
   <mkdir dir="${dist}/lib"/>
<copy todir="${build}/lib" verbose="true" file="lib/someLib-5.0.2.jar" />

       <!-- Put everything in ${build} into the MyProject-${DSTAMP}.jar file -->
       <jar jarfile="${dist}/lib/myProject-${DSTAMP}.jar" basedir="${build}">

       <manifest>
            <attribute name="Main-Class" value="com.nik.mypackage.MainClass"/>
            <attribute name="Class-Path" value="../lib/someLib.jar"/>
       </manifest>
</jar>
</target>

The jar MyProject-20111126.jar is getting created. However, running the below command:

c:>java -jar MyProject-20111126.jar

is throwing a NoClassDefFoundError for a class in someLib.jar

What am I doing wrong ??

Thanks for reading!

Upvotes: 1

Views: 666

Answers (2)

Vicky
Vicky

Reputation: 17355

As mentioned in the comment by Eric Rosenberg, we can not nest jar files inside other jar files. So we need to deflat the library and bundle individual classes in the app jar.

Upvotes: 0

Eric Rosenberg
Eric Rosenberg

Reputation: 1533

When you run where is someLib.jar relative to the MyProject-20111126.jar?

The classpath you are setting up in the MyProject.jar is telling the VM to look for a lib folder in the parent directory of MyProject.jar.

The ClassPath entry in the manifest is interpreted relative to the location of the JAR file. It is used to locate jar files on the File System. The regular class loader in JAVA does not support JAR files bundled inside of JAR files.

Upvotes: 1

Related Questions