Java类加载器 - 如何引用不同版本的jar [英] Java Classloader - how to reference different versions of a jar

查看:1026
本文介绍了Java类加载器 - 如何引用不同版本的jar的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个常见的问题。我使用2个库 A.jar B.jar ,这些依赖于同一个jar的不同版本。

假设在运行时我需要 THIS.xxxjar

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

我可以编译特定的jar(A.jar / B.jar )反对它的依赖,但在运行时,我只能加载1版本。哪一个?

只加载1个依赖项(最新版本)意味着如果库不是向后兼容的(有没有后向兼容库,那么我的代码可能会抛出运行时异常)。

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?).

无论如何,我知道像OSGi这样的东西可以解决这个问题。

我想知道什么是旧的方式来解决这种问题...

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...

感谢很多

推荐答案

老方式你提到(和一个OSGI当然是使用的)是为您的依赖关系的两个分支安装自己的ClassLoader。例如,应用程序服务器能够在同一个JVM中运行相同应用程序的旧版本和较新版本。

"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.

阅读有关classloader层次结构的信息。

Read about classloader hierarchy.

在您的设置中,棘手的部分是两个分支的课程相遇的联合点。两个分支都不能使用加载到另一个的类。使其工作的方法是确保只有由引导类加载器(JRE类)或MYBUG的类加载器加载的类才能传递到两个分支。

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.

这篇关于Java类加载器 - 如何引用不同版本的jar的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆