自定义文件类加载器
package cn.xqh.reflection;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
public class FileSystemClassLoader extends java.lang.ClassLoader{
private String rootdir;
public FileSystemClassLoader(String rootdir) {
this.rootdir=rootdir;
}
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
Class c = findLoadedClass(name);
if(null!=c) {
return c;
}else {
ClassLoader parent = this.getParent();
try {
c = parent.loadClass(name);
} catch (Exception e) {
}
if(null!=c) {
return c;
}else {
byte[] b =getclassdata(name);
if(null==b) {
throw new ClassNotFoundException();
}else {
c = defineClass(name, b, 0, b.length);
return c;
}
}
}
}
private byte[] getclassdata(String name) {
String path = rootdir + "/"+ name.replace(".", "/")+".class";
InputStream is = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
is = new FileInputStream(path);
byte[] car = new byte[1024];
int temp = 0;
while((temp=is.read(car))!=-1) {
bos.write(car, 0, temp);
}
return bos.toByteArray();
} catch (Exception e) {
e.printStackTrace();
return null;
}finally {
if(is!=null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}