AdrianF
AdrianF

Reputation: 75

Java class loading - which class loader and/or class caused loading?

I'm aware that by using the flag verbose:class, we can get the jvm to log out when a class is loaded and from where. However, I want to see some additional information - which class loader loaded the class, and ideally the class which was being executed that caused the loading. (Not entirely sure that latter part even make sense!)

Is there any way to get the jvm to log this info, or any other suggestions of how to get it? Thanks

Upvotes: 2

Views: 3395

Answers (2)

Espen Brekke
Espen Brekke

Reputation: 404

If your problem is debuging classloading I would consider using a debugger.

Using intellij i was able to set a breakpoint in the url-classloader. You can configure this breakpoint to log a custom message instead of breaking.

If you want to be able to turn this on in production you could of course write your own classloader.

This isn't dificult, but you will have to figure out how to log to the logging framework without logging the loading of the loading framework. I guess the easiest way would be to ignore some predefined packages when logging. If you choose this route I can probably provide you with a shell of a solution. Just ask.

Upvotes: 1

AlBlue
AlBlue

Reputation: 24060

You can see what triggered a class load in some cases if you use -XX:+TraceClassLoading and -XX:+TraceClassResolution you'll see a collection of Loading messages (when the .class bytes get loaded) and subsequent RESOLVE messages when the classes themselves get resolved. So by figuring out which RESOLVE messages you're seeing you should be able to determine which class is causing a dependent class to be loaded.

Unfortunately this doesn't tell you anything about your classloaders. So although it will print out the JAR that it's loading from, if that doesn't uniquely identify your classloader then it may not be possible to answer the question using standard tools. However, if you're using an embedded engine such as Tomcat or OSGi that provide their own classloaders, there may be additional debugging flags that you can turn on in order to identify which classloader instance is being used.

Upvotes: 3

Related Questions