Monday, November 23, 2009

ClassNotFoundException, I hate you

I've been writing Java for some time now, about 5 years or so, and I always have problems with the classpath. I guess my problem is I don't care to understand it, I just need it to work.

Regardless, I was writing a simple Ant script this weekend, and after the build and Jar-ing of the assets, I would execute. Over and over I would get class not found exceptions when running the Jar.

Why? Why? Why? I set the libraries on the command line via argument -cp. All the external Jars are in the local "lib" directory. What could be the issue? Ah, when you package the Jar, the manifest needs the classpath! I get it.

The following is my Jar task I used...

<jar destfile="${dist.dir}/${prop.jarname}.jar" basedir="${build.dir}">
<manifest>
<attribute name="Main-Class" value="com.exec.Main" />
<attribute name="Class-Path" value="${lib.list}"/>
</manifest>
</jar>

Since I have more then one external Jar needed on the class path for my application, I need a list of Jars.

First I need my master classpath set for the build, and I will reuse it for my Jar...

<path id="master.classpath">
<fileset dir="${lib.dir}"><include name="**/*.jar"/></fileset>
</path>

Now I will reference this in my library list for the manifest...

<manifestclasspath property="lib.list" jarfile="${prop.jarname}.jar">
<classpath refid="master.classpath"/>
</manifestclasspath>
This took me like 3 hours to figure out. So I felt like posting it.

See Also...

Share on Twitter