2

I am looking for a way to reload a class into Java at runtime. The motivation is to make debugging more efficient. The application is a typical client/server design that synchronously processes requests. A "handler" object is instantiated for each request. This is the only class I intend to dynamically replace. Since each request deals with a fresh instance, reloading this class won't have any side-effects. In short, I do not want to restart the entire application every time there is a change to this module.

In my design, the Java process becomes aware that a .class file has been updated in the classpath in between requests. When this happens, the "handler" class is unloaded and a new one is loaded.

I know I can use the classLoader interface to load in a new class. I seem to be having trouble finding the proper way of "unloading".

4

3 回答 3

4

如果没有对它们的剩余引用,类将像任何其他对象一样被卸载和垃圾收集。这意味着必须没有可访问的类实例(由该特定类加载器实例加载),并且类加载器实例本身也必须符合垃圾回收条件。

所以基本上,你所要做的就是创建一个新的类加载器实例来加载新版本的类,并确保没有对旧版本实例的引用。

于 2010-11-16T13:41:00.493 回答
1

我相信您实际上需要具有类加载器的层次结构,并且为了重新加载您实际上摆脱了低级类加载器(通过 normall GC 手段),因此它加载的所有类。据我所知,Java EE 应用程序服务器使用这种技术重新加载应用程序,当加载到一个类加载器中的框架代码想要使用加载到其他地方的类时,会有各种有趣的结果。

于 2010-11-16T13:43:52.827 回答
0

截至 2015 年,java 的类重新加载也是一个缺失的功能。

  • 使用OSGi创建类重载应用程序。
  • 使用 jrebel 进行测试。还有一些其他人做同样的事情。
  • 使用应用程序服务器并将要重新加载的部分外部化到单独的 Web 应用程序中。然后继续部署/取消部署。由于悬挂旧的 ClassLoader 实例,您最终会得到一些 perm gen 空间溢出类型的错误。
  • 使用脚本运行器来执行部分可变代码。JSR-223 Java Scripting API 支持脚本语言“Java”。

我写了一个关于类重载的系列。但所有这些方法都不利于生产。

恕我直言,此类重新加载在 java 中很混乱,不值得尝试。但我非常希望这是 java 中的规范。

于 2015-07-14T05:33:37.410 回答