Karl
Karl

Reputation: 2945

Where did this class come from?

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?

Upvotes: 4

Views: 426

Answers (6)

unmaskableinterrupt
unmaskableinterrupt

Reputation: 408

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

Upvotes: 0

Yishai
Yishai

Reputation: 91881

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.

Upvotes: 0

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147164

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.

Upvotes: 3

Maurice Perry
Maurice Perry

Reputation: 32831

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

Upvotes: 2

Syntactic
Syntactic

Reputation: 10961

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();

Upvotes: 5

Related Questions