自定义一个类加载器

 1 import java.io.ByteArrayOutputStream;
 2 import java.io.File;
 3 import java.io.FileInputStream;
 4 import java.nio.ByteBuffer;
 5 import java.nio.channels.Channels;
 6 import java.nio.channels.FileChannel;
 7 import java.nio.channels.WritableByteChannel;
 8 
 9 /**
10  * 自定义类加载器
11  * @ClassName MyClassLoader
12  * @Author xxx
13  * @Version V1.0
14  **/
15 public class MyClassLoader extends ClassLoader {
16 
17     private File fileObject;
18 
19     public void setFileObject(File fileObject) {
20         this.fileObject = fileObject;
21     }
22 
23     public File getFileObject() {
24         return fileObject;
25     }
26 
27     @Override
28     protected Class<?> findClass(String name) throws ClassNotFoundException {
29         try {
30             byte[] data = getClassFileBytes(this.fileObject);
31             return defineClass(name, data, 0, data.length);
32         } catch (Exception e) {
33             e.printStackTrace();
34             return null;
35         }
36 
37     }
38 
39     /**
40      * 从文件中读取去class文件
41      *
42      * @throws Exception
43      */
44     private byte[] getClassFileBytes(File file) throws Exception {
45         //采用NIO读取
46         FileInputStream fis = new FileInputStream(file);
47         FileChannel fileC = fis.getChannel();
48         ByteArrayOutputStream baos = new ByteArrayOutputStream();
49         WritableByteChannel outC = Channels.newChannel(baos);
50         ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
51         while (true) {
52             int i = fileC.read(buffer);
53             if (i == 0 || i == -1) {
54                 break;
55             }
56             buffer.flip();
57             outC.write(buffer);
58             buffer.clear();
59         }
60         fis.close();
61         return baos.toByteArray();
62     }
63 
64 }

重点:需要继承

ClassLoader 类,并重写
findClass()方法。注意:官方不建议重写loadClass()方法,可能会破坏双亲委托机制。

使用这个自定义类加载器时,先
1 MyClassLoader myClassLoader = new MyClassLoader();
2 myClassLoader.setFileObject(new File("此处填需要加载的class文件全路径"));
3 Class<?> test = myClassLoader.findClass("Test");
4 System.out.println(test.getClassLoader());

这个test的类加载器就是自定义的

MyClassLoader !

 


posted @ 2020-08-02 00:53  线形的眼泪  阅读(140)  评论(0编辑  收藏  举报