除了可以用系統默認的類加載器,我們還可以用實現自己的類加載器,類加載器實現步驟如下:
1.定義一個類繼承ClassLoader
2.重寫findClass方法,用來查找具體的類字節碼
3.實例化自定義的類加載器,調用loadClass即可加載類
下面我們來自定義一個類加載器,加載我們自己路徑的類字節碼
package com.jvm.demo;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
/**
* 自定義類加載器
* @author liuxg
* @date 2016年5月23日 下午5:52:29
*/
public class CustomClassLoader extends ClassLoader{
private String rootPath ;
/**
* 類的路徑
* @param rootPath
*/
public CustomClassLoader(String rootPath) {
this.rootPath = rootPath ;
}
/**
* 根據name來尋找該類
*
*/
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
Class<?> c = findLoadedClass(name);
if (c == null) { //內存堆中還沒加載該類
c = findMyClass(name); //自己實現加載類
}
return c ;
}
/**
* 加載該類
* @param name
* @return
*/
private Class<?> findMyClass(String name) {
String path = rootPath + "/" + name.replace(".", "/") + ".class" ;
try {
File file = new File(path); //獲取文件
if (file.exists()) {
byte[] bytes = FileUtils.readFileToByteArray(file);//利用org.apache.commons.io包來讀取字節
return this.defineClass(null, bytes,0,bytes.length); //調用父類方法,生成具體類
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
使用我們自己的類加載器
public class Demo02 {
public static void main(String[] args) {
CustomClassLoader loader = new CustomClassLoader("D://myclass");
try {
Class<?> clazz = loader.loadClass("com.myclass.Demo03");
System.out.println(clazz);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
有了類加載器,你可以實現從任意地方加載資源,例如硬盤,http,ftp,類路徑等等