Java - how to load different versions of the same class?

倾然丶 夕夏残阳落幕 提交于 2019-11-26 17:28:40
helios

You're going the right way. You must take some things into account.

The normal thing is classes that exist in parent classloaders are used. So if you want two versions those classes must not be there.

But if you want to interact you can use reflection, or even better a common interface. So I'll do this:

common.jar:
BaseInterface

v1.jar:
SomeImplementation implements BaseInterface

v2.jar:
OtherImplementation implements BaseInterface

command-line:
java -classpath common.jar YourMainClass
// you don't put v1 nor v2 into the parent classloader classpath

Then in your program:

loader1 = new URLClassLoader(new URL[] {new File("v1.jar").toURL()}, Thread.currentThread().getContextClassLoader());
loader2 = new URLClassLoader(new URL[] {new File("v2.jar").toURL()}, Thread.currentThread().getContextClassLoader());

Class<?> c1 = loader1.loadClass("com.abc.Hello");
Class<?> c2 = loader2.loadClass("com.abc.Hello");

BaseInterface i1 = (BaseInterface) c1.newInstance();
BaseInterface i2 = (BaseInterface) c2.newInstance();

You have almost written the solution. I hope the following code fragment will help.

ClassLoader cl = new URLClassLoader(new URL[] {new File("v1.jar").toURL()}, Thread.currentThread().getContextClassLoader());
Class<?> clazz = cl.loadClass("Hello");

Replace v1.jar by v2.jar and this code will load version #2.

it depends on what are u going to do with both versions and how, but in general you can at least load 2 version of class in different classloaders, and then set the Thread.contextClassloader() and play...

see http://www.javaworld.com/javaqa/2003-06/01-qa-0606-load.html and http://docs.oracle.com/javase/jndi/tutorial/beyond/misc/classloader.html

Atul Soman

For a sample implementation of the accepted answer by @helios checkout github.com/atulsm/ElasticsearchClassLoader

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!