package com.wuyiccc.jvm.classloader;
import java.io.*;
/**
* @author wuyiccc
* @date 2020/3/10 21:32
* 岂曰无衣,与子同袍~
*/
public class MyTest16 extends ClassLoader {
private String classLoaderName;
private final String fileExtension = ".class";
public MyTest16(String classLoaderName) {
super();
this.classLoaderName = classLoaderName;
}
public MyTest16(ClassLoader parent, String classLoaderName) {
super(parent); // 显示指定该类加载器的父加载器
this.classLoaderName = classLoaderName;
}
@Override
public String toString() {
return "[" + this.classLoaderName + "]";
}
@Override
protected Class<?> findClass(String className) throws ClassNotFoundException {
byte[] data = this.loadClassData(className);
return this.defineClass(className, data, 0, data.length);
}
private byte[] loadClassData(String name) {
InputStream is = null;
byte[] data = null;
ByteArrayOutputStream baos = null;
try {
// this.classLoaderName = this.classLoaderName.replace(".", "/"); // 对 . 换成 / 路径
name = name.replace(".", "/");
is = new FileInputStream(new File(name + this.fileExtension));
baos = new ByteArrayOutputStream();
int ch = 0;
while (-1 != (ch = is.read())) {
baos.write(ch);
}
data = baos.toByteArray();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
is.close();
baos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return data;
}
public static void main(String[] args) throws IllegalAccessException, InstantiationException, ClassNotFoundException {
MyTest16 loader1 = new MyTest16("loader1");
test(loader1);
}
public static void test(ClassLoader classLoader) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
Class<?> clazz = classLoader.loadClass("com.wuyiccc.jvm.classloader.MyTest1"); // loadClass 会调用findClass方法
Object object = clazz.newInstance();
System.out.println(object);
}
}
18.自定义类加载器
最新推荐文章于 2024-08-16 23:08:28 发布