Where's That Class Coming From?

| | Comments (0) | TrackBacks (0)

Fun things happen in Java when you have the same class in two different places in your CLASSPATH. For example, maybe your application server has decided to bundle an open source package in their product but has not repackaged it, which can cause hours of fun debugging the problem. Another common example is, or at least used to be, XML parsers. Anyway, if you ever need to find out exactly where a class is being loaded from, you can plop a few simple lines of code in your application somewhere, run it, and Voila! you now at least know which JAR is causing you headaches which might help you figure out how to solve your problem.

The only reason I remembered how to do this was because Stu Halloway showed this trick in a No Fluff Just Stuff session on class loading years ago. The code is pretty simple, and here it is:

Class aClass = EmbeddedDriver.class;
ProtectionDomain protectionDomain = aClass.getProtectionDomain();
CodeSource codeSource = protectionDomain.getCodeSource();
if (codeSource != null) {
    URL location = codeSource.getLocation();
    System.out.println("location = " + location);
}

The output I received when trying to find where the Apache Derby EmbeddedDriver was being loaded from looked like this:


location = file:/Users/sleberkn/Workspace/learning_derby/lib/derby.jar

You could also print out information about the ProtectionDomain and CodeSource for additional information. For example, here's what I got:

protectionDomain = ProtectionDomain  (file:/Users/sleberkn/Workspace/learning_derby/lib/derby.jar <no signer certificates>)
 sun.misc.Launcher$AppClassLoader@a9c85c
 <no principals>
 java.security.Permissions@5740bb (
 (java.io.FilePermission /Users/sleberkn/Workspace/learning_derby/lib/derby.jar read)
 (java.lang.RuntimePermission exitVM)
)


codeSource = (file:/Users/sleberkn/Workspace/learning_derby/lib/derby.jar <no signer certificates>)
location = file:/Users/sleberkn/Workspace/learning_derby/lib/derby.jar

The information contained in the ProtectionDomain can be very useful as it tells you information about class loaders, permissions, etc. Another trick, which maybe I'll write about some other time, is to find out which class loader is loading a particular class. The code is also simple as you basically just walk the tree of class loaders until there are no more. This can aid in debugging JEE applications that package things in EAR, EAR, and EJB-JAR files, as the various class loading schemes of application servers can be, well, annoying to say the least.

Leave a comment

0 TrackBacks

Listed below are links to blogs that reference this entry: Where's That Class Coming From?.

TrackBack URL for this entry: http://www.nearinfinity.com/mt/mt-tb.cgi/558