自定義ClassLoader直接繼承ClassLoader抽象類, 覆寫
protected Class<?> findClass(String name) throws ClassNotFoundException
方法, 實(shí)現(xiàn)自定義加載類. 在 #ClassLoader抽象類中, 給出了 class實(shí)例化方法:
protected final Class<?> defineClass(byte[] b, int off, int len)
這個(gè)方法目的是將 class字節(jié)流轉(zhuǎn)為 class instance
/**
* Converts an array of bytes into an instance of class <tt>Class</tt>.
* Before the <tt>Class</tt> can be used it must be resolved.
*
* <p> This method assigns a default {@link java.security.ProtectionDomain
* <tt>ProtectionDomain</tt>} to the newly defined class. The
* <tt>ProtectionDomain</tt> is effectively granted the same set of
* permissions returned when {@link
* java.security.Policy#getPermissions(java.security.CodeSource)
* <tt>Policy.getPolicy().getPermissions(new CodeSource(null, null))</tt>}
* is invoked. The default domain is created on the first invocation of
* {@link #defineClass(String, byte[], int, int) <tt>defineClass</tt>},
* and re-used on subsequent invocations.
*
* <p> To assign a specific <tt>ProtectionDomain</tt> to the class, use
* the {@link #defineClass(String, byte[], int, int,
* java.security.ProtectionDomain) <tt>defineClass</tt>} method that takes a
* <tt>ProtectionDomain</tt> as one of its arguments. </p>
*
* @param name
* The expected <a href="#name">binary name</a> of the class, or
* <tt>null</tt> if not known
*
* @param b
* The bytes that make up the class data. The bytes in positions
* <tt>off</tt> through <tt>off+len-1</tt> should have the format
* of a valid class file as defined by
* <cite>The Java™ Virtual Machine Specification</cite>.
*
* @param off
* The start offset in <tt>b</tt> of the class data
*
* @param len
* The length of the class data
*
* @return The <tt>Class</tt> object that was created from the specified
* class data.
*
* @throws ClassFormatError
* If the data did not contain a valid class
*
* @throws IndexOutOfBoundsException
* If either <tt>off</tt> or <tt>len</tt> is negative, or if
* <tt>off+len</tt> is greater than <tt>b.length</tt>.
*
* @throws SecurityException
* If an attempt is made to add this class to a package that
* contains classes that were signed by a different set of
* certificates than this class (which is unsigned), or if
* <tt>name</tt> begins with "<tt>java.</tt>".
*
* @see #loadClass(String, boolean)
* @see #resolveClass(Class)
* @see java.security.CodeSource
* @see java.security.SecureClassLoader
*
* @since 1.1
*/
protected final Class<?> defineClass(String name, byte[] b, int off, int len)
throws ClassFormatError
{
return defineClass(name, b, off, len, null);
}
這里是從本地文件系統(tǒng)中通過文件的方式讀取*.class文件, 將獲取到的全部class文件字節(jié)流傳遞給 #defineClass方法, 實(shí)例化. 這之后我們就可以使用這個(gè)類對象了.
public class MyClassLoader extends ClassLoader {
private String dir ;
public MyClassLoader(String dir) {
//
this.dir = dir ;
}
@Override
public Class<?> findClass(String name) throws ClassNotFoundException {
//
if (StringUtils.isBlank(name))
throw new ClassNotFoundException() ;
String path = this.getPath(name) ;
byte[] ret = this.getClassData(path) ;
if (ret == null)
throw new ClassNotFoundException("讀取".concat(path).concat("失敗.")) ;
return defineClass(name, ret,0, ret.length) ;
}
private byte[] getClassData(String path) {
System.out.println("Path: - ".concat(path));
try {
InputStream inputStream = new FileInputStream(new File(path)) ;
ByteArrayOutputStream baos = new ByteArrayOutputStream() ;
byte[] buffer = new byte[1024] ;
while (inputStream.read(buffer) != -1) {
// baos.write(buffer);
baos.write(buffer, 0, buffer.length);
}
return baos.toByteArray() ;
} catch (Exception e) {
e.printStackTrace();
}
return null ;
}
private String getPath(String className) {
return this.dir.concat(className.replace(".", File.separator)).concat(".class") ;
}
}
隨便定一個(gè)使用自定義類加載器加載的類:
public class ABean {
public ABean() {
System.out.println("初始化ABean.");
}
@Override
public String toString() {
return "hello, myClassLoader...." ;
}
}
測試類:
public static void main(String[] args) {
//JVM-classLoader test
String dir = "/test/target/classess/test/jvm/",
clsName = "test.jvm.ABean" ;
MyClassLoader myClassLoader = new MyClassLoader(dir) ;
try {
Class cls = myClassLoader.loadClass(clsName) ;
System.out.println(cls.newInstance().toString()) ;
} catch (Exception e) {
e.printStackTrace();
}
}
//輸出
初始化ABean.
hello, myClassLoader....
注意
需要注意的是
protected final Class<?> defineClass(String name, byte[] b, int off, int len)
這個(gè)方法第一個(gè)參數(shù)是指: 類全名[Full-className] 否則會(huì)有異常: java.lang.NoClassDefFoundError 這里我根據(jù)方法文檔, 大概是因?yàn)?
* @throws NoClassDefFoundError
* If <tt>name</tt> is not equal to the <a href="#name">binary
* name</a> of the class specified by <tt>b</tt>
在讀取class文件得到的byteStream名稱為 test/jvm/ABean/class 但是傳遞給#defineClass方法的名稱卻是 ABean.
以上代碼測試環(huán)境為
Linux arch 4.14.10-1-ARCH x86_64 GNU/Linux
觸發(fā)類加載有以下三種方式:
- 命令行啟動(dòng)應(yīng)用時(shí)候由JVM初始化加載
- 通過Class.forName()方法動(dòng)態(tài)加載
- 通過ClassLoader.loadClass()方法動(dòng)態(tài)加載
類裝載器把一個(gè)類裝入JVM中逗抑,要經(jīng)過以下步驟:
- 裝載:查找和導(dǎo)入Class文件;
- 鏈接:把類的二進(jìn)制數(shù)據(jù)合并到JRE中峦树; 這個(gè)過程包括三個(gè)步驟:
- 校驗(yàn):檢查載入Class文件數(shù)據(jù)的正確性;
- 準(zhǔn)備:給類的靜態(tài)變量分配存儲(chǔ)空間君账;
- 解析:將符號引用轉(zhuǎn)成直接引用座柱;
- 初始化:對類的靜態(tài)變量焕梅,靜態(tài)代碼塊執(zhí)行初始化操作