代码改变世界

设计一个类加载器

2018-09-09 21:55  小兵故事  阅读(224)  评论(0编辑  收藏  举报

类加载器用于实现类的加载动作,但它在Java程序中起到的作用远远不限于类加载阶段。对于任何一个类,都需要由加载它的类加载器和这个类本身来决定其在Java虚拟机中的唯一性

 1 package com.study.classLoad;
 2 
 3 import java.io.IOException;
 4 import java.io.InputStream;
 5 /**
 6  * 设计一个简单的类加载器
 7  * @author xiaojuan
 8  *
 9  */
10 public class ClassLoaderTest {
11 
12     public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
13         // TODO Auto-generated method stub
14         ClassLoader myLoader = new ClassLoader(){
15 
16             @Override
17             public Class<?> loadClass(String name)
18                     throws ClassNotFoundException {
19                 try {
20                     //String filename = "com.study.classLoad.ClassLoaderTest";
21                     String filename = name.substring(name.lastIndexOf(".") + 1) + ".class";
22                     InputStream is = getClass().getResourceAsStream(filename);
23                     if (is == null) {
24                         return super.loadClass(name);
25                     }
26                     byte[] b = new byte[is.available()];
27                     is.read(b);
28                     return defineClass(name, b, 0, b.length);
29                 } catch (IOException e) {
30                     throw new ClassNotFoundException();
31                 }
32                 
33             }
34             
35         };
36         Object obj = myLoader.loadClass("com.study.classLoad.ClassLoaderTest").newInstance();
37         System.out.println(obj.getClass());
38         System.out.println(obj instanceof com.study.classLoad.ClassLoaderTest);
39         
40     }
41 
42 }