views:

109

answers:

6

How would you go about establishing where a class ( or maybe resource ) has been loaded from?

I am trying to work out exactly where a class has been loaded from. Does anyone know if you can find out the following:

  1. Which Jar file did the class come from ?
  2. What classloader loaded the file?
+5  A: 

The class Class has an instance method getClassLoader() that returns a reference to the class loader that loaded the class it represents. Note that this can return null. See here.

So, if you wanted to know which classloader loaded String (just as an example) you could do:

ClassLoader loader = String.class.getClassLoader();

or:

ClassLoader loader = "I'm a String".getClass().getClassLoader();
Syntactic
Which would probably be `null`. Also class loaders often load classes and resources from multiple locations.
Tom Hawtin - tackline
+2  A: 

You can get an URL by calling MyClass.class.getResource("MyClass.class") for instance.

Maurice Perry
+2  A: 

For a class one solution is MyClass.class.getProtectionDomain().getCodeSource().getLocation(). (Actually, may have a null ProtectionDomain or that may not hava a CodeSource. My also throw a SecurityException.

Tom Hawtin - tackline
A: 

I would go about that with the -verbose:class command line option, saving the output to a text file and then use grep (or the DOS find if you are windows) to see details on how that class is loaded.

Yishai
A: 

if you have an instance of the class insta.getClass().getClassLoader().getName() -->this is the classloader that loaded the class

insta.getClass().getProtectionDomain().getCodeSource().getLocation()- where the class was loader from

unmaskableinterrupt