ITeye博客

Java ClassLoader深入研究(二)

outlaw · 2011-01-22 15:40 · 编程语言 · Cache · C · Java · C++ · thread · Markdown

五、关于两个ClassLoader载入同一个类

注意:由两个不同的ClassLoader载入的同一个类,其是不同类型的,因此如果进行赋值会报ClassCastException

示例:

 

view plaincopy to clipboardprint?

  1. package Test;
  2. import java.io.*;
  3. import java.util.*;
  4. public class TestClassLoader extends ClassLoader {
  5. protected Map<String, Class> cache = new HashMap<String, Class>();
  6. public TestClassLoader() {
  7. super();
  8. }
  9. protected Class<?> findClass(String name) throws ClassNotFoundException {
  10. if (cache.get(name) != null) {
  11. return cache.get(name);
  12. }
  13. try {
  14. String tname = name.replace('.', '/');
  15. File file = new File("c://" + tname + ".class");
  16. FileInputStream in = new FileInputStream(file);
  17. BufferedInputStream bufIn = new BufferedInputStream(in);
  18. ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
  19. BufferedOutputStream bufOut = new BufferedOutputStream(byteOut);
  20. byte[] buffer = new byte[4096];
  21. int len = -1;
  22. while((len = bufIn.read(buffer)) != -1) {
  23. bufOut.write(buffer, 0, len);
  24. }
  25. bufOut.flush();
  26. byteOut.flush();
  27. byte[] data = byteOut.toByteArray();
  28. Class cls = defineClass(name, data, 0, data.length);
  29. cache.put(name, cls);
  30. return cls;
  31. } catch (IOException e) {
  32. e.printStackTrace();
  33. }
  34. return null;
  35. }
  36. }
  37. class TestLoaderA {
  38. public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
  39. TestClassLoader loader = new TestClassLoader();
  40. System.out.println(TestAImp1.class.getClassLoader());
  41. System.out.println(loader.findClass("Test.TestAImp1").getClassLoader());
  42. TestAImp1 test = (TestAImp1)loader.findClass("Test.TestAImp1").newInstance();
  43. test.test();
  44. }
  45. }
  46. public class TestAImp1 extends AbstractTestA {
  47. public void test() {
  48. System.out.println(Thread.currentThread().toString());
  49. System.out.println("Test");
  50. }
  51. }

 

 运行以上代码结果:

sun.misc.Launcher$AppClassLoader@197d257
Test.TestClassLoader@1b90b39
Exception in thread "main" java.lang.ClassCastException: Test.TestAImp1
 at Test.TestLoaderA.main(TestClassLoader.java:84)

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。