动态类重新加载仅在调试模式下工作,为什么/如何真正起作用? [英] Dynamic class reloading works only in debug mode, why/ how it really works?
问题描述
我有一个棘手的问题。
我的java程序在循环中做这样的事情:
My java program is doing in a loop such things:
循环:
-
将带有已编译java类的外部文件读入byte []数组。
read external file with compiled java class into byte[] array.
创建我自己的类加载器的新实例。
create a new instance of my own classloader.
从readed文件到这个classloader实例的setbytes。
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.
问题出在哪里。
-
当我在调试模式下运行此程序时,它的行为与我期望的一样,因此如果外部文件更改了类加载器,则加载新版本的类并执行新版本(如果文件没有更改)它当然也加载旧版本。)
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).
但是当我运行这个程序而不是在调试模式下它总是执行旧版本,尽管readed文件的事实已经改变了。
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.
也许对类加载问题和JVM行为有更深入了解的人可以解释我这种行为。
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:
- JVM加载类和其他资源只能从CLASSPATH环境变量中指定的目录或Jars中进入类路径(除非在调试模式下运行)。
- 为此,它使用ClassLoaders
- 一旦ClassLoader实例加载了一个资源,它就会保留在内存中,直到ClassLoader被垃圾收集。
调试模式是JVM提供的一种特殊模式,类加载器更加努力地为您提供最新版本的资源。
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屋!