User实体类:
public class User implements Serializable{
private long id;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
}
CustomClassLoaderDemo实体类:
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class CustomClassLoaderDemo {
public static void main(String[] args) throws IllegalAccessException, InstantiationException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
System.out.println("classLoader = " + classLoader);
String className = "com.qgw.web.classloader.User";
String classFileName = className.replace(".", "/").concat(".class");
String classPath = System.getProperty("user.dir") + "/springboot-rest/target/classes";
File classFile = new File(classPath, classFileName);
System.out.println(classFile.getAbsolutePath());
MyClassLoader myClassLoader = new MyClassLoader();
Class<?> userClass = myClassLoader.defineClass(className, classFile);
Object user = userClass.newInstance();
Method setMethod = userClass.getDeclaredMethod("setId", long.class);
Method getMethod = userClass.getDeclaredMethod("getId");
setMethod.invoke(user, 100);
long id = (long)getMethod.invoke(user);
System.out.printf("主键ID = [%s]", id);
}
static class MyClassLoader extends ClassLoader {
public MyClassLoader() {
super(Thread.currentThread().getContextClassLoader());
}
public Class<?> defineClass(String name, File classFile) {
// File --> byte[]
byte[] bytes = loadBytes(classFile);
return defineClass(name, bytes, 0 , bytes.length);
}
private byte[] loadBytes(File classFile) {
byte[] bytes = null;
try {
bytes = FileUtils.readFileToByteArray(classFile);
} catch (IOException e) {
e.printStackTrace();
}
return bytes;
}
}
}