Java ClassLoader深入研究(二)
五、关于两个ClassLoader载入同一个类
注意:由两个不同的ClassLoader载入的同一个类,其是不同类型的,因此如果进行赋值会报ClassCastException
示例:
view plaincopy to clipboardprint?
- package Test;
- import java.io.*;
- import java.util.*;
- public class TestClassLoader extends ClassLoader {
- protected Map<String, Class> cache = new HashMap<String, Class>();
- public TestClassLoader() {
- super();
- }
- protected Class<?> findClass(String name) throws ClassNotFoundException {
- if (cache.get(name) != null) {
- return cache.get(name);
- }
- try {
- String tname = name.replace('.', '/');
- File file = new File("c://" + tname + ".class");
- FileInputStream in = new FileInputStream(file);
- BufferedInputStream bufIn = new BufferedInputStream(in);
- ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
- BufferedOutputStream bufOut = new BufferedOutputStream(byteOut);
- byte[] buffer = new byte[4096];
- int len = -1;
- while((len = bufIn.read(buffer)) != -1) {
- bufOut.write(buffer, 0, len);
- }
- bufOut.flush();
- byteOut.flush();
- byte[] data = byteOut.toByteArray();
- Class cls = defineClass(name, data, 0, data.length);
- cache.put(name, cls);
- return cls;
- } catch (IOException e) {
- e.printStackTrace();
- }
- return null;
- }
- }
- class TestLoaderA {
- public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
- TestClassLoader loader = new TestClassLoader();
- System.out.println(TestAImp1.class.getClassLoader());
- System.out.println(loader.findClass("Test.TestAImp1").getClassLoader());
- TestAImp1 test = (TestAImp1)loader.findClass("Test.TestAImp1").newInstance();
- test.test();
- }
- }
- public class TestAImp1 extends AbstractTestA {
- public void test() {
- System.out.println(Thread.currentThread().toString());
- System.out.println("Test");
- }
- }
运行以上代码结果:
sun.misc.Launcher$AppClassLoader@197d257
Test.TestClassLoader@1b90b39
Exception in thread "main" java.lang.ClassCastException: Test.TestAImp1
at Test.TestLoaderA.main(TestClassLoader.java:84)