I have a tricky question.
My java program is doing in a loop such things:
loop:
read external file with compiled java class into byte[] array.
create a new instance of my own classloader.
setbytes from the readed file to this instance of classloader.
using created classloader create a new instance of object of the class from external file.
call any method of the created object.
And where the problem is.
When I run this program in debug mode it behaves as I expect, so if external file changed classloader loads new version of class and executes new version (if file didn't change it loads old version also of course).
But when I run this program NOT in a debug mode it always executes old version despite the fact that the readed file has changed.
Maybe someone with a deeper knowledge of classloading issues and JVM behaviours can explain me this behaviour.
Here's a simplified version of what happens:
- The JVM loads classes and other resources into the classpath exactly once (unless running in debug mode) from the directories or Jars specified in the CLASSPATH environment variable.
- To do this, it uses ClassLoaders
- Once a resource has been loaded by a ClassLoader instance, it remains in memory until the ClassLoader is garbage collected.
The debug mode is a special mode provided by the JVM, and the classloader works harder to give you the latest version of the resource.
It is not possible to reload the same class with the same class loader
you can find a well written article about dynamic class re/loading here
来源:https://stackoverflow.com/questions/10581127/dynamic-class-reloading-works-only-in-debug-mode-why-how-it-really-works