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

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

问题描述

这是一个常见的问题.我使用了 2 个库 A.jarB.jar,它们依赖于同一个 jar 的不同版本.
假设在运行时我需要 THIS.x.x.x.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

我可以根据其依赖项编译特定的 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.

阅读类加载器层次结构.

Read about classloader hierarchy.

在你的设置中,棘手的部分是联合点,来自两个分支的类在这里相遇.两个分支都不能使用加载到另一个分支中的类.使其工作的方法是确保只有引导类加载器(JRE 类)或 MY.jar 的类加载器加载的类被传递到两个分支.

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 Classloader - 如何引用不同版本的 jar的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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