Java - 如何加载同一类的不同版本? [英] Java - how to load different versions of the same class?

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

问题描述

我已经阅读了很多关于 Java 类加载器的文章,但到目前为止我还没有找到这个简单问题的答案:

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

我在 jars v1.jarv2.jar 中有两个版本的 com.abc.Hello.class.我想在我的应用程序中同时使用两者.最简单的方法是什么?

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]

在不同的班级:

Classloader myClassLoader = [magic that includes v2.jar and ignores v1.jar]
Hello hello = myclassLoader.load[com.abc.Hello]

我想避免使用 OSGi.

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

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

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