自定义ClassLoader
程序员文章站
2022-06-05 20:24:45
1. 将Message.java拷贝到 /Users/sunny/test目录下(和NVIDIAClassLoader类MESSAGE_CLASS_PATH指定的路径一致),并编译生成字节码文件(.class)。 2.编写自定义ClassLoader类。 3.测试类。 运行结果: ......
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