ecology_maven/aiyh/utils/HotDeployToolUtil.java

75 lines
1.8 KiB
Java

package aiyh.utils;
import aiyh.utils.zwl.common.ToolUtil;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
/**
* @author EBU7-dev1-ayh
* @date 2021/8/25 0025 10:53
* 热部署 自定义类加载器
*/
public class HotDeployToolUtil extends ClassLoader {
ToolUtil toolUtil = new ToolUtil();
private final String classpath;
private final String className;
public HotDeployToolUtil(String classpath, String className) {
this.classpath = classpath;
this.className = className;
}
@Override
public Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
Class<?> loadedClass = findLoadedClass(name);
// 需要我自己去加载
if (loadedClass == null) {
loadedClass = findClass(name);
if (loadedClass != null) {
return loadedClass;
}
}
return super.loadClass(name, resolve);
}
@Override
public Class<?> findClass(String name) throws ClassNotFoundException {
if (name.startsWith("java.")) {
return getSystemClassLoader().loadClass(name);
}
byte[] data;
String classPath = name.replace(".", System.getProperties().getProperty("file.separator")) + ".class";
try {
data = this.loadClassData(classPath);
} catch (Exception e) {
e.printStackTrace();
return null;
}
return this.defineClass(name, data, 0, data.length);
}
public byte[] loadClassData(String name) throws Exception {
FileInputStream inputStream;
try {
toolUtil.writeDebuggerLog(classpath + name);
inputStream = new FileInputStream(classpath + name);
// 定义字节数组输出流
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int b = 0;
while ((b = inputStream.read()) != -1) {
baos.write(b);
}
inputStream.close();
return baos.toByteArray();
} catch (Exception e) {
e.printStackTrace();
throw new ClassNotFoundException();
}
}
}