繼承自系統(tǒng)的ClassLoader
class FileSystemClassloader extends ClassLoader
實(shí)現(xiàn)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數(shù)組
private byte[] getClassData(String name) {
//包名轉(zhuǎn)成文件路徑
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;
}
路徑轉(zhuǎn)化,將包名轉(zhuǎn)化為實(shí)際的硬盤路徑
private String pathForClassName(String name) {
String path = rootDir+File.separator+name.replace(".", File.separator)+".class";
System.out.println("path-->"+path);
return path;
}
類 FileSystemClassLoader的 findClass()方法首先根據(jù)類的全名在硬盤上查找類的字節(jié)代碼文件(.class 文件)瞳抓,然后讀取該文件內(nèi)容,最后通過 defineClass()方法來把這些字節(jié)代碼轉(zhuǎn)換成 java.lang.Class類的實(shí)例土匀。