自定义类加载器,破坏双亲委派机制
可以选择继承classLoader或者URLClassLoader
package com.example.demo;
import lombok.SneakyThrows;
import java.io.*;
/**
* @author dh
*/
public class UserDefineClassLoader extends ClassLoader{
private String rootPath;
public UserDefineClassLoader( String rootPath) {
this.rootPath = rootPath;
}
@SneakyThrows
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
//转换为以文件路径表示的文件
String path = classTofileName(name);
//获取指定路径的class文件的二进制流数据
byte[] data = getbyteFromPath(path);
//自定义ClassLoader 内部调用defineClass
return defineClass(name,data,0,data.length);
}
private byte[] getbyteFromPath(String filePath) throws IOException {
FileInputStream stream = null;
ByteArrayOutputStream baos = null;
try {
stream = new FileInputStream(filePath);
baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = stream.read()) != -1){
baos.write(buffer,0,len);
}
return baos.toByteArray();
} catch (IOException e) {
throw new RuntimeException(e);
}finally {
stream.close();
baos.close();
}
}
private String classTofileName(String name) {
return rootPath+"\\"+name.replace(".","\\");
}
}