How to load a jar file at runtime [duplicate] How to load a jar file at runtime [duplicate] java java

How to load a jar file at runtime [duplicate]


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();

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.

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

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.


This works for me:

File file  = new File("c:\\myjar.jar");URL url = file.toURL();  URL[] urls = new URL[]{url};ClassLoader cl = new URLClassLoader(urls);Class cls = cl.loadClass("com.mypackage.myclass");


I was asked to build a java system that will have the ability to load new code while running

You might want to base your system on OSGi (or at least take a lot at it), which was made for exactly this situation.

Messing with classloaders is really tricky business, mostly because of how class visibility works, and you do not want to run into hard-to-debug problems later on. For example, Class.forName(), which is widely used in many libraries does not work too well on a fragmented classloader space.