继承自系统的ClassLoader
class FileSystemClassloader extends ClassLoader
实现findClass()
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
byte[] data = getClassData(name);
if (data == null) {
throw new ClassNotFoundException();
}else {
return defineClass(name, data, 0, data.length);
}
}
通过文件输入流获取.class文件的byte数组
private byte[] getClassData(String name) {
//包名转成文件路径
String path = pathForClassName(name);
FileInputStream fis = null;
try {
fis = new FileInputStream(path);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int len = 0;
byte[] buffer = new byte[1024];
while ((len = fis.read(buffer))!= -1) {
bos.write(buffer, 0, len);
}
bos.flush();
return bos.toByteArray();
} catch (Exception e) {
e.printStackTrace();
}finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
路径转化,将包名转化为实际的硬盘路径
private String pathForClassName(String name) {
String path = rootDir+File.separator+name.replace(".", File.separator)+".class";
System.out.println("path-->"+path);
return path;
}
类 FileSystemClassLoader的 findClass()方法首先根据类的全名在硬盘上查找类的字节代码文件(.class 文件),然后读取该文件内容,最后通过 defineClass()方法来把这些字节代码转换成 java.lang.Class类的实例。