Saturday 26 May 2007

Shed light on a classloading mystery

Have you ever struggled with class loading problems like java.lang.NoClassDefFoundError or having the java compiler or jre telling you that a class signature is different than you expect it to be?
The latter is often because the class you thought was classloaded actually was loaded from another location but in a different version than you expected.

To shed light on the classloading mystery I have used the following bash command with success:

$ for i in `find . -name *.jar`; do echo $i; jar tvf $i | grep [a name of a class]; done

A quick explanation:
- for i in `find . -name *.jar`; It iterates through all found jar files in the actual directory and any subdirectory.
- echo $i; Then it echoes the path and filename for any jar file it finds.
- jar tvf $i | grep [a name of a class]; Executing a jar tvf *(testing a jar unpack) and piping it into a grep will print any line containing the text you search for.

Simple example where I locate all Tapestry BasePage classes (and sourcefiles) in my maven 2 repository:

jeyben@vilfortpark ~/.m2/repository/org/apache/tapestry
$ ls -l
total 0
drwx------+ 3 jeyben Ingen 0 May 12 20:56 tapestry-annotations
drwx------+ 3 jeyben Ingen 0 May 12 20:56 tapestry-contrib
drwx------+ 3 jeyben Ingen 0 May 12 20:57 tapestry-core
drwx------+ 4 jeyben Ingen 0 May 12 20:54 tapestry-framework
drwx------+ 3 jeyben Ingen 0 May 12 20:57 tapestry-ioc
drwx------+ 5 jeyben Ingen 0 May 12 20:57 tapestry-project

jeyben@vilfortpark ~/.m2/repository/org/apache/tapestry
$ for i in `find . -name *.jar`; do echo $i; jar tvf $i | grep BasePage; done
./tapestry-annotations/4.1.1/tapestry-annotations-4.1.1.jar
./tapestry-contrib/4.1.1/tapestry-contrib-4.1.1.jar
./tapestry-core/5.0.1/tapestry-core-5.0.1.jar
./tapestry-framework/4.1/tapestry-framework-4.1-sources.jar
1172 Fri Jul 07 02:04:04 2006 org/apache/tapestry/html/BasePage.java
./tapestry-framework/4.1/tapestry-framework-4.1.jar
540 Fri Jul 28 14:33:34 2006 org/apache/tapestry/html/BasePage.class
./tapestry-framework/4.1.1/tapestry-framework-4.1.1-sources.jar
1181 Fri Nov 10 13:26:26 2006 org/apache/tapestry/html/BasePage.java
./tapestry-framework/4.1.1/tapestry-framework-4.1.1.jar
540 Sun Dec 17 02:36:28 2006 org/apache/tapestry/html/BasePage.class

No comments: