自定义ClassLoader

 

1.  将Message.java拷贝到 /Users/sunny/test目录下(和NVIDIAClassLoader类MESSAGE_CLASS_PATH指定的路径一致),并编译生成字节码文件(.class)。

Message.java:
1 package com.nvidia.util;
2 
3 public class Message {
4     public void send() {
5         System.out.println("www.nvidia.com");
6     }
7 }

2.编写自定义ClassLoader类。

NVIDIAClassLoader.java:
 1 package com.nvidia.util;
 2 
 3 import java.io.ByteArrayOutputStream;
 4 import java.io.File;
 5 import java.io.FileInputStream;
 6 import java.io.InputStream;
 7 
 8 public class NVIDIAClassLoader extends ClassLoader{
 9     private static final String MESSAGE_CLASS_PATH = File.separator +"Users" + File.separator + "sunny" + File.separator + "test" + File.separator+"Message.class";
10     public Class<?> loadData(String className) throws Exception{
11         byte[] data = this.loadClassData();
12         if(data != null) {
13             return super.defineClass(className, data, 0, data.length);
14         }
15         return null;
16     }
17     private byte[] loadClassData() throws Exception{
18         InputStream input = null;
19         ByteArrayOutputStream bos = null;
20         byte data[] = null;
21         try {
22             bos = new ByteArrayOutputStream();
23             input = new FileInputStream(new File(MESSAGE_CLASS_PATH));
24             input.transferTo(bos);
25             data = bos.toByteArray();
26         } catch (Exception e) {
27             e.printStackTrace();
28         }finally {
29             if(input != null) {
30                 input.close();
31             }
32             if(bos != null) {
33                 bos.close();
34             }
35         }
36         return data;
37     }
38 }

 

3.测试类。

JavaReflectDemo:
 1 package com.nvidia.demo;
 2 
 3 import com.nvidia.util.NVIDIAClassLoader;
 4 import java.lang.reflect.Method;
 5 
 6 public class JavaReflectDemo {
 7     public static void main(String[] args) throws Exception {
 8         NVIDIAClassLoader classloader = new NVIDIAClassLoader();
 9         Class<?> cls = classloader.loadData("com.nvidia.util.Message");
10         //System.out.println(cls);
11         Object object = cls.getDeclaredConstructor().newInstance();
12         Method method = cls.getDeclaredMethod("send");
13         method.invoke(object);
14         System.out.println(cls.getClassLoader());
15         System.out.println(cls.getClassLoader().getParent());
16         System.out.println(cls.getClassLoader().getParent().getParent());
17     }
18 }

运行结果:

www.nvidia.com
com.nvidia.util.NVIDIAClassLoader@5451c3a8
jdk.internal.loader.ClassLoaders$AppClassLoader@55054057
jdk.internal.loader.ClassLoaders$PlatformClassLoader@2c7b84de

 

点赞