How do I keep track when class is loaded and destroyed in jvm? Is there any callback method that is exposed by the jvm?
If are ok with using JRockit JVM, you can make use of the APIs below, which will give you callback methods when a class is loaded and class is unloaded.
Have a look at JVM class from which we are supposed to use the getClassLibrary()
method.
On the classLibrary object we can register listeners for classloading events which gives the class names etc.
You can add the command line option -verbose:class
to your Java process, this will
display information about each class loaded.
You can use static block to detect class loading but you can not detect class unloading. In java all classes loaded through the system classloader will never be unloaded and all classes loaded through other classloaders will be unloaded only when the classloader is unloaded.
static{
//execute when the class will be loaded
}
From Java 9 onward, you can use -Xlog. e.g.:
java -Xlog:class+load -Xlog:class+unload ...
This will print entries like:
[0.296s][info][class,load] java.lang.Shutdown source: jrt:/java.base
[0.296s][info][class,load] java.lang.Shutdown$Lock source: jrt:/java.base
You can also use -Xlog:help
to get more information on the option.
Do you want this information in your application or do you just want to analyse that from the outside? In the latter case you maybe can use VisualVM for that. Maybe your question is related to this one: Loaded classes in VisualVM.
You can add Java Opts to see which class is loaded via:
java -verbose:class
About destroyed class, I am not sure.