实现一个自定义类加载器来加载指定目录上的类
package com.bootdo.springBoot.classloader;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class MyClassLoader extends ClassLoader {
private String directory;
public MyClassLoader(String directory){
this.directory=directory;
}
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
String fileName=name;
if(fileName.indexOf(".")!=-1){
fileName.replace("\\.","\\\\");
}
fileName=fileName+".class";
System.out.println(directory+";"+fileName);
try{
try(FileInputStream in=new FileInputStream(directory+fileName)){
try(ByteArrayOutputStream out=new ByteArrayOutputStream()){
byte[] b=new byte[1024];
int len=0;
while((len=in.read(b))!=-1){
out.write(b,0,len);
}
byte[] data=out.toByteArray();
return defineClass(data,0,data.length);
}
}
}catch (IOException e) {
throw new ClassNotFoundException();
}
}
public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
MyClassLoader myClassLoader=new MyClassLoader("E:\\springsourcecode\\bootdo\\bootdo\\src\\main\\java\\com\\bootdo\\springBoot\\classloader\\");
Class c=myClassLoader.loadClass("Test");
Object test=c.newInstance();
Method method=c.getMethod("show",String.class);
method.invoke(test,"liurong");
}
}
以上的自定义类类加载器可以加载指定目录下的类。