java 引用不同版本jar包,Java类加载器 - 如何引用不同版本的jar

This is a common problem. I'm using 2 libraries A.jar and B.jar and these depend on different versions of the same jar.

Let's say that at runtime I need THIS.x.x.x.jar

MY.jar

-> A.jar -> THIS.1.0.0.jar

-> B.jar -> C.jar -> THIS.5.0.0.jar

I can compile the specific jar (A.jar/B.jar) against its dependency but at runtime I've to load only 1 version. Which one?

Loading only 1 dependency (the latest version) means that my code will probably throw runtime exceptions if the libraries are not Backward Compatible (are there Backward Compatible libraries out there?).

Anyway I know that something like OSGi can fix this issue.

I'm wondering what's the old way to fix this kind of problems...

Thanks a lot

解决方案

"Old way" you mentioned (and the one OSGI certainly uses under the hood) is to install your own ClassLoader for both branches of your dependencies. That's how, for instance, application servers are able to run both older and newer versions of the same application inside the same JVM.

Read about classloader hierarchy.

In your setup, the tricky part is the joint point, where classes from both branches meet. Neither branches can use classes loaded into another one. The way to make it work is to make sure only classes loaded by boot classloader (JRE classes) or classloader of MY.jar are passed down to both branches.

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值