免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1519 | 回复: 0
打印 上一主题 下一主题

fighting with the tricky ClassLoader [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2005-08-07 00:40 |只看该作者 |倒序浏览

The conceptions of ClassLoader are the most tricky ones in the javaworld...
一想到Reflection, ClassLoader就像做恶梦, 但他们确实非常有趣, 每一个问题都是一个挑战. 和这些东西鏖战几个月后, 经过无数测试, 今天又弄明白一个概念, 所以写下来, 希望能对大家有所帮助, 同时也加深我的记忆.
假设有两个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博客,如果查看原文请点:http://blog.chinaunix.net/u/4960/showart_39476.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP