NoClassDefFound error for a jar created using ant

2019-08-04 07:13发布

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!

标签: java ant build jar
2条回答
劳资没心,怎么记你
2楼-- · 2019-08-04 07:48

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.

查看更多
倾城 Initia
3楼-- · 2019-08-04 07:53

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.

查看更多
登录 后发表回答