如何在运行时加载jar文件 [英] How to load a jar file at runtime

查看:162
本文介绍了如何在运行时加载jar文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我被要求构建一个能够在运行时加载新代码(扩展)的java系统。
如何在代码运行时重新加载jar文件?或者我如何加载一个新的jar?

I was asked to build a java system that will have the ability to load new code (expansions) while running. How do I re-load a jar file while my code is running? or how do I load a new jar?

显然,由于恒定的正常运行时间非常重要,我想添加重新加载现有类的能力。它(如果它不会使事情变得太复杂)。

Obviously, since constant up-time is important, I'd like to add the ability to re-load existing classes while at it (if it does not complicate things too much).

我应该注意哪些事项?
(把它想象成两个不同的问题 - 一个关于在运行时重新加载类,另一个关于添加新类)。

What are the things I should look out for? (think of it as two different questions - one regarding reloading classes at runtime, the other regarding adding new classes).

推荐答案

使用现有数据重新加载现有类可能会破坏事情。

Reloading existing classes with existing data is likely to break things.

您可以相对轻松地将新代码加载到新的类加载器中:

You can load new code into new class loaders relatively easily:

ClassLoader loader = URLClassLoader.newInstance(
    new URL[] { yourURL },
    getClass().getClassLoader()
);
Class<?> clazz = Class.forName("mypackage.MyClass", true, loader);
Class<? extends Runnable> runClass = clazz.asSubclass(Runnable.class);
// Avoid Class.newInstance, for it is evil.
Constructor<? extends Runnable> ctor = runClass.getConstructor();
Runnable doRun = ctor.newInstance();
doRun.run();

不再使用的类加载器可以被垃圾收集(除非存在内存泄漏,通常是使用ThreadLocal,JDBC驱动程序, java.beans 等)的情况。

Class loaders no longer used can be garbage collected (unless there is a memory leak, as is often the case with using ThreadLocal, JDBC drivers, java.beans, etc).

如果你想保留对象数据,然后我建议一个持久性机制,如序列化,或任何你习惯的。

If you want to keep the object data, then I suggest a persistence mechanism such as Serialisation, or whatever you are used to.

当然,调试系统可以做更好的事情,但是更hacky和更不可靠。

Of course debugging systems can do fancier things, but are more hacky and less reliable.

可以在类加载器中添加新类。例如,使用 URLClassLoader.addURL 。但是,如果一个类无法加载(因为,例如,你还没有添加它),那么它将永远不会加载到该类加载器实例中。

It is possible to add new classes into a class loader. For instance, using URLClassLoader.addURL. However, if a class fails to load (because, say, you haven't added it), then it will never load in that class loader instance.

这篇关于如何在运行时加载jar文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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