Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
982 views
in Technique[技术] by (71.8m points)

java - how to load same class from different jars

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

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.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...