Dynamic class reloading works only in debug mode, why/ how it really works?

你说的曾经没有我的故事 提交于 2019-12-22 11:04:15

问题


I have a tricky question.

My java program is doing in a loop such things:

loop:

  1. read external file with compiled java class into byte[] array.

  2. create a new instance of my own classloader.

  3. setbytes from the readed file to this instance of classloader.

  4. using created classloader create a new instance of object of the class from external file.

  5. call any method of the created object.

And where the problem is.

  1. 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).

  2. 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.


回答1:


Here's a simplified version of what happens:

  1. 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.
  2. To do this, it uses ClassLoaders
  3. 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.




回答2:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!