2
votes

Yesterday i thought one question ,below is the detail:

I have 3 JAR files, a.jar, b.jar ,c.jar . both these jars files have a class named com.test.Test ,and sayHello() was defined in this class.

I create a web application, i reference a.jar,b.jar,c.jar . And in main method, i involve sayHello(); .at this time, which com.test.Test will be load?

the result is a.jar.

any body tell me the reason ?? thanks in advance!!!

4
you can easily test it yourself by making sayHello method print something slightly different from one to the others. - gigadot
yes, i did this. a.jar was loaded. i want to know why :) - user1698495
oh sorry. i missed the part that you answered your own question. - gigadot

4 Answers

3
votes

That is what java language specification says. It loads what ever the class first occurs in classpath and ignores other.

1
votes

Instead of focusing on which one will be loaded, realize that the stuff within the JAR files probably need their com.test.Test class instead of someone else's com.test.Test to work properly. That means for a functional system you'll have to make a way that a.jar finds a.jar's com.test.Test instead of the one in b.jar. The same goes for b.jar finding it's classes in preference to a.jar's.

The only way to do this is to use a framework which adds name spacing beyond the java package mechanism. This is typically done with multiple classloaders, often one for each JAR file. You can write such a thing yourself (Tomcat did), where you need to specify the rules for cross-loader discovery, or use something akin to a OSGi framework.

0
votes

Whichever Jar File comes first in your classpath will be used.. You can modify your CLASSPATH environment variable to the path of your Jar file

Suppose you modify it as below: -

set CLASSPATH = %CLASSPATH%;.;a.jar;b.jar

then a.jar will be used..

You can also modify it by: -

set CLASSPATH = %CLASSPATH%;.;b.jar;a.jar

In this case, b.jar will be used.. These commands you need to run from your Command Line..

** NOTE: - If you are using any IDE, then they don't use System Classpath.. You need to set different classpath for the IDE you are using..

0
votes

If you are using an IDE, such as eclipse, you can modify your classpath on the properties of the project, then go to Build Path, and then you have the Order and Export tab where you can move up and down the jars. The one of the top will be the first taken by your application.

This you can also do manually by editing the file called "classpath" which is on your project and move to the top the jar you want your application to use first.