自定義類加載器:
因爲系統的ClassLoader只會加載指定目錄下的class文件,如果你想加載自己的class文件,那麼就可以自定義一個ClassLoader。而且我們可以根據自己的需求,對class文件進行加密和解密,自定義類加載器步驟如下:
- 繼承抽象類ClassLoader;
- 重寫findclass(String name)方法;
- 調用defineClass(String name, byte[] b, int off, int len)方法;
// 自定義類加載器
public class MyClassLoader extends ClassLoader{
/**指定加載路徑*/
private String path;
public MyClassLoader(String classpath) {
path = classpath;
}
/**
*
* @param name 類的全限定名
* @return 該類的Class實例
* @throws ClassNotFoundException
*/
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
// 獲取class文件的字節碼數組
byte[] classByte = getClassByte(name);
if (classByte!=null){
// 將字節碼數組轉換成Class類實例
return defineClass(name,classByte,0,classByte.length);
}
throw new ClassNotFoundException(name);
}
/**
*
* @param name 類的全限定名
* @return class文件的字節碼數組
*/
private byte[] getClassByte(String name){
String path = this.path+name.replace(".","/").concat(".class");
File file = new File(path);
if (file.exists()){
FileInputStream fis = null;
ByteArrayOutputStream baos = null;
try {
fis = new FileInputStream(file);
baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int size = 0;
while ((size=fis.read(buffer))!=-1){
baos.write(buffer,0,size);
}
}catch (Exception e){
e.printStackTrace();
}finally {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return baos.toByteArray();
}
return null;
}
}
// 被加載測試類
public class ClassLoaderTest {
public void say(){
System.out.println("load ClassLoaderTest class successfully!");
}
}
// 測試類
public class Test {
public static void main(String[] args) throws Exception {
MyClassLoader myClassLoader = new MyClassLoader("/Users/teihin/projects/");
String name = "com.test.ClassLoaderTest";
Class<?> classLoaderTest = myClassLoader.loadClass(name);
System.out.println("類加載器是:"+classLoaderTest.getClassLoader());
// 利用反射獲取say方法
Method method = classLoaderTest.getMethod("say");
Object object = classLoaderTest.newInstance();
method.invoke(object);
}
}
// 輸出結果:
類加載器是:intron.classtest.classload.MyClassLoader@1d44bcfa
load ClassLoaderTest class successfully!
Tomcat類加載器:
Tomcat 擁有不同的自定義類加載器,以實現對各種資源庫的控制。一般來說,Tomcat主要用類加載器解決以下4個問題:
- 同一個Web服務器裏,各個web項目之間各自使用Java類庫要互相隔離;
- 同一個Web服務器裏,各個Web項目之間可以提供共享的java類庫;
- 爲了使服務器不受web項目的影響,應該使服務器的類庫與應用程序類庫互相獨立;
- 對於支持JSP的Web服務器,應該支持熱插拔功能;