Reputation: 5262
Is there a way to determine during run-time where a specific class is loaded from?
We are using an application server which has several places to put external libraries. Now there is the problem that, for example, several different versions of an apache-commons library is put in different places and nobody can actually tell which of those JAR files is the source in a specific Java class.
Is there a way to ask the class loader where it actually has been loading the class from? What the specific JAR file is?
Upvotes: 2
Views: 252
Reputation: 18834
This information is stored in a classes ProtectionDomain
. You can access the protection domain of a class using:
Object o = new Object();
ProtectionDomain protection = o.getClass().getProtectionDomain();
Inside the this object, there is a method called getCodeSource()
that returns a CodeSource
that contains the url of the location it came from:
URL loadedFile = protection.getCodeSource().getLocation();
This url can be null if the classloader didn't provide this information while it was loading.
Upvotes: 4
Reputation: 18764
I would prefer to use Verbose class loading to diagnose class loading problems.
It can be enabled using -verbose:class
as a JVM argument. This prints out classes when they are loaded, including their jar file names.
Some questions related to this: Java verbose class loading
Upvotes: 1
Reputation: 146
Another way to find where a class is loaded from (without manipulation to the source) is to start the Java VM with the option: -verbose:class
.
Upvotes: 1