如何从不同的罐子加载相同的类 [英] how to load same class from different jars

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

问题描述

我在两个不同的jar jar1&中有一个Client.java类。 jar2
现在在运行时我想决定加载哪个Client.class如

I have a class Client.java in two different jars jar1 & jar2 Now at run time i want to decide which Client.class loaded like

if (country==india){
         // load Client class of jar1
) else{
        load client class from jar2 
}

我可以这么做......

can i do that...

推荐答案

如果2个班级有相同的包名称,即com.mycompany.Client,然后您最终会在某种情况下加载哪个版本的Client。它归结为首先在类路径上。这是一个JAR地狱的情况 http://en.wikipedia.org/wiki/Java_Classloader#JAR_hell

If the 2 classes have the same package name, i.e. com.mycompany.Client, then you end up in a situation where it is somewhat arbitrary which version of Client is loaded. It comes down to which is on the classpath first. This is a JAR hell situation http://en.wikipedia.org/wiki/Java_Classloader#JAR_hell.

这是一个要避免的好情况,但如果你绝对必须拥有相同类的不同版本,那么有办法做到这一点。一种方法是使用自定义类加载器,类加载器将知道您需要执行哪个版本。这不是一件容易的事情,也很难管理。 OSGi框架是一种帮助管理它的替代方案(它使用自定义类加载器),但如果你只有一个类的实例,我就不会使用它,因为它是另一个需要时间和维护的框架。

This is a good situation to avoid but if you absolutely must have different versions of the same class, there are ways to do it. One way is to use a custom classloader and the classloader will know which version you need to do. This is not a trivial thing to do and can be difficult to manage. The OSGi framework is an alternative to help manage this (it uses custom classloaders under the hood), but I wouldn't use that if you just have one instance of a class as it is another framework that takes time and maintenance.

底线:如果可以,请避开这种情况,如果不能,请采取阻力最小的路径。

Bottom line: avoid the situation if you can and take the path of least resistance if you cannot.

如果是班级确实有不同的包名,@ Casidiablo提供了一个很好的答案。

If the classes do have different package names, @Casidiablo has provided a good answer.

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

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