我可以动态卸载和重新加载(相同的其他版本)JAR 吗? [英] Can I dynamically unload and reload (other versions of the same) JAR?

查看:19
本文介绍了我可以动态卸载和重新加载(相同的其他版本)JAR 吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个服务器程序,用于运行 API 的单元测试(显示大量信息并提供网络访问以控制/监控整个事情)...

I am writing a server program which is used to run unit tests of an API (displaying lots of information and providing web access to control / monitor the whole thing)...

此 API 在编译时为服务器所知并提供作为 JAR.

This API is known to the server during compile time and is provided as a JAR.

能够比较不同版本的单元测试结果API 的(无需重新启动服务器),我希望能够卸载 API 的当前"版本,并重新加载新的(或旧的).

To be able to compare between unit test results of different versions of the API (without restarting the server), I want to be able to unload the 'current' version of the API, and to reload a newer one (or an older one).

我不想使用 URLClassLoader 并调用每一个按名称的方法
(使用 getDeclaredMethod("someMethod") ),
因为服务器严重依赖 API 而它会以这种肮脏的方式包装"每个方法调用很复杂.

I don't want to use URLClassLoader and invoke every single method by name
( using getDeclaredMethod("someMethod") ),
because the server heavily depends on the API and it would be complicated to 'wrap' every method call in such dirty way.

我在想:由于 JAR 的所有版本的所有接口相同,我不能以某种方式重新加载其他版本吗的 JAR(没有那个按名称调用?).

I was thinking: Since all interfaces of all versions of the JAR are same, couldn't I do it by somehow reloading an other version of the JAR (without that by-name-invokation?).

注意:我使用的是最新的 Java SE (6) 和 Java EE (5).

如果你认为我想要实现的目标是不可能的,请提出解决方法"或不同的概念.

If you think, what I'm trying to achieve is not possible, please suggest a 'workaround' or a different concept.

推荐答案

我想如果你使用

Class.forName(clsname, init, classloader); 

(Javadoc 此处)您将获得给定类加载器提供的类的实例.由于该类加载的所有内容也将通过相同的类加载器加载.

(Javadoc here) you will get an instance of the class provided by the given classloader. Everything loaded because of that class will also be loaded via the same classloader.

只要您非常小心地处理从现在开始实例化的对象(以允许 GC),您就应该能够重新加载不同的版本.我之前用 Java 1.3 做过一次,这需要大量调试,但最后我有一个引导"应用程序,它按名称加载了一个 Runnable 类并且能够软重启"通过针对不同的 URL 实例化一个新的类加载器并再次运行.

As long as you're very careful with the objects instantiated from this point on (to allow for GC), you should be able to reload different versions. I did this once before with Java 1.3, it took a lot of debugging, but at the end I had a "bootstrap" application that loaded a Runnable class by name and was able to "soft-restart" by instantiating a new classloader against a different URL and going again.

这篇关于我可以动态卸载和重新加载(相同的其他版本)JAR 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆