- 論壇徽章:
- 0
|
The conceptions of ClassLoader are the most tricky ones in the javaworld...
一想到Reflection, ClassLoader就像做惡夢(mèng), 但他們確實(shí)非常有趣, 每一個(gè)問題都是一個(gè)挑戰(zhàn). 和這些東西鏖戰(zhàn)幾個(gè)月后, 經(jīng)過無數(shù)測(cè)試, 今天又弄明白一個(gè)概念, 所以寫下來, 希望能對(duì)大家有所幫助, 同時(shí)也加深我的記憶.
假設(shè)有兩個(gè)ClassLoader, parentLoader and childLoader, parentLoader is the parent classloader of the childLoader. Now, according to java's defalt delegation class loading mechanism, when the child class loader wants to load a class, say com.foo.Bar, it first asks his father, hey, dad, do you have the class com.foo.Bar previously loaded or in your classpath, then, recursively, the father does the same thing. If the father answered yes, then it returned the class to his son, if not, he told the son, no, I don't have it previously loaded or in my classpath, finally, the son search his own classpath, if it still can not find the class in his own classpath, then, a ClassNotFoundException thrown. This is the story in the java class loading world.
Now the child class loader hopes to get a class com.foo.Bar. but the class is found in the parent class loader's classpath.
ClassLoader parentLoader = new URLClassLoader(someURLs, null);
ClassLoader childLoader = new URLClassLoader(someOtherUrls, parentLoader);
Class c = childLoader.loadClass("com.foo.Bar");
Method m = c.getMethod("main", new Class[] { args.getClass() });
m.invoke(null, new Object[] { args });
Now, everything is happening in the new world(classpath). And, suddenly, a ClassNotFoundException is thrown when loading a class within the child class loader occured. Then, I move the class desired in to the father's classpth, it returns calm. So we see, everything is now happening in the father's world!! We load a class from the child class loader, but the class is actually found in the father's class loader, and we invoke a method on the class loaded. Then next time within the method, it load a new class, it search from the parent class loader, not the child. Really tricky!
本文來自ChinaUnix博客,如果查看原文請(qǐng)點(diǎn):http://blog.chinaunix.net/u/4960/showart_39476.html |
|