java加载同名类,Java - 如何加载不同版本的同一个类?

I have read a lot about Java classloaders, but so far I have failed to find an answer for this simple question:

I have two versions of com.abc.Hello.class in jars v1.jar and v2.jar. I want to use both in my application. What is the simplest way of doing this ?

I don't expect to be that simple, but something along these lines would be awesome :

Classloader myClassLoader = [magic that includes v1.jar and ignores v2.jar]

Hello hello = myclassLoader.load[com.abc.Hello]

And in a different class :

Classloader myClassLoader = [magic that includes v2.jar and ignores v1.jar]

Hello hello = myclassLoader.load[com.abc.Hello]

I would like to avoid using OSGi.

解决方案

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值