Paul Moore Paul Moore - 4 months ago 18
Java Question

How do I diagnose Java ClassNotFound exception happening in scripting languages but not Java code

I am trying to use Joda Time in Java on Windows. I've downloaded Joda Time 1.2 and put the JAR on my CLASSPATH:

PS D:\Java\Jars> $env:CLASSPATH
.;C:\Program Files\Java\jre6\lib\ext\QTJava.zip;D:\Java\Jars\joda-time-2.1.jar


The following Java code works perfectly:

import org.joda.time.*;

class Foo {
public static void main (String[] args) {
System.out.println("Hello, world");
DateTime d = new DateTime();
DateTime b = new DateTime(1981,12,25,0,0);
Period p = new Period(b,d);
System.out.println(p.toString());
}
}


However, when I try to import joda time from a scripting language, I get ClassNotFound errors.

Jython:

PS D:\Java\Jars> java -jar .\jython.jar
Jython 2.5.2 (Release_2_5_2:7206, Mar 2 2011, 23:12:06)
[Java HotSpot(TM) Client VM (Sun Microsystems Inc.)] on java1.6.0_31
Type "help", "copyright", "credits" or "license" for more information.
>>> from org.joda.time import DateTime
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named joda
>>> import os
>>> os.getenv("CLASSPATH")
'.;C:\\Program Files\\Java\\jre6\\lib\\ext\\QTJava.zip;D:\\Java\\Jars\\joda-time-2.1.jar'


Clojure:

PS D:\Java\Jars> java -jar .\clojure-1.4.0.jar
Clojure 1.4.0
user=> (import (org.joda.time DateTime Period))
ClassNotFoundException org.joda.time.DateTime java.net.URLClassLoader$1.run (:-1)


How can I diagnose what is going wrong here? Presumably there is something specific to the scripting environments that is causing the issue. I know Python, but I'm not very familiar with the Java-interop aspects of Jython. I know little about Clojure beyond enough to set up the above test.

The classpath within Jython seems fine, as shown.

Answer

You are running both programs directly out of their JAR's:

java -jar archive.jar

Which does not use the system class path. An executable JAR must be bundled with all it's dependencies. Try this simple alternative for testing purposes:

java -cp "D:\Java\Jars\joda-time-2.1.jar;D:\Java\Jars\clojure-1.4.0.jar" clojure.main

Which will run the Clojure command line evaluator, with the Joda Time libraries included. Something similar should be available for Jython as well.