同一类 java_Java – 如何加载同一类的不同版本?

你正确的方式。 你必须考虑一些事情。

正常的事情是使用父类加载器中存在的类。 所以,如果你想要两个版本,那些类不能在那里。

但是如果你想互动,你可以使用reflection,甚至更好的通用接口。 所以我会这样做:

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、付费专栏及课程。

余额充值