tags:

views:

71

answers:

5

Hello,

I'm currently getting to know Java and OSGi, so I've read a few books. In one particular book the class loading is described.

You can download it (free and legal) from the authors page (Neil Bartlett): OSGi Book

On page 9 and 10 are this pictures:

alt textalt text

It seems like there is the possibility that our class "Foo" won't use the class "Bar" of foobar.jar, but instead class "Bar" from naughty.jar.

Because of the flat and global structure of the Java classpath this could be, but as far as I know you would define a package from where you want to import a certain class:

import foobar.Bar

This should prevent loading the wrong class, shouldn't it? Of course assuming that the package is called "foobar".

+2  A: 

good idea, but unfortunately packages are independent of the jar file names. you can have things in arbitrary packages all in the same jar file, and arbitrary jar file names with unrelated package names. it's up to the classloader to resolve them for you.

oedo
+4  A: 

The import statement has nothing to do with classloading - it just allows you to use short name Bar instead of the fully qualified foobar.Bar. If both foobar.jar and naughty.jar contain class with fully qualified name foobar.Bar, classloader will load the class from the from the first jar file with required class on the classpath.

axtavt
Unless the package is sealed or has different signers.
Tom Hawtin - tackline
Parent class loader delegation is an issue too, not just the class path. If naughty.jar is handled by a parent `ClassLoader` then the classes in it will always be resolved first (though a sealed package keeps this from happening as well).
Kevin Brock
Thank you for your answer axtavt. But this also means if the "Bar" class from foobar.jar is in package "hello" (hello.Bar) and the "Bar" class from naughty.jar is in the package "evil" (evil.Bar) there won't be any problems? Since the fully qualified names are different. There only would be a problem if in both jars the package in which the "Bar" class is located would be the same?
Jens
@Jens: Yes, you won't have any problems if fully qualifiead names are different.
axtavt
+1  A: 

The problem is both foobar.jar and naughty.jar might have a class that its fully qualified name is foobar.Bar. Then foobar.Foo resolves the foobar.Bar of naughty.jar instead of foobar.Bar of foobar.jar.

Hope this helps.

Bytecode Ninja
A: 

The author is assuming here that both versions of the Bar classes are in the same package (or there wouldn't be any problem). What the author is describing can happen if naughty.jar is "first" in the class path. In that case, the classloader would pick the naughty version (the classloader scans the classpath in the natural order and picks the first class found).

Pascal Thivent
A: 

The import doesnt allow you the liberty of loading the class from the desired java. You can read more about classloaders from here Java Classloaders

harshit