May 13 2008

Where was this class loaded from?!

Tags: , , Rajiv @ 9:54 am GMT-0700

There are many ways to figure out where a class is being loaded from. Naveen uses the -verbose flag of the JVM to figure out where a class is being loaded from. If you are using Pramati Server, then you can use the command: who_load_me to find out which classloader loaded the class, the classloader hierarchy and where the class was loaded from.

Another way to find out where a class was loaded from is by using the getCodeSource method, like so:

public static void which(Class aClass) throws Exception {
    System.out.println(aClass.getProtectionDomain().getCodeSource().getLocation());
}

I used to use this so much that Ravi finally decided to check it into cvs. Thanks buddy! Lot of people wondered why I always called it which, it is in memory of the Unix command which, which would tell you the directory in the PATH variable from which the shell was picking up the exectuable from.

And if you are coming for an interview and give this as the answer to my question, you better be able to explain what a protection domain is and when/by-whom is the codeSource set.

Update: I was inspired to blog about this after I spoke with Deepak about this. I didn’t know he had a blog and he had blogged about the same topic too!