开发者

Trying to understand Java Classloading

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 text http://img265.imageshack.us/img265/4127/picture1qct.pngalt text http://img297.imageshack.us/img297/594/picture2yv.png

It seems like there is the possib开发者_如何学Goility 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".


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.


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.


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.


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜