接着上篇博客,下面我們來看看如何自定義類加載器
自定義類加載器
JVM中除根類加載器之外的所有類加載器都是ClassLoader子類的實例,開發者可以通過擴展ClassLoader的子類,並重寫該ClassLoader所包含的方法來實現自定義的類加載器。
ClassLoader類有如下兩個關鍵方法:
- loadClass(String name, boolean resolve): 該方法爲ClassLoader的入口點,根據指定名稱來加載類,系統就是調用ClassLoader的該方法來獲取指定類對應的Class對象。
- findClass(String name): 根據指定名稱來查找類。
/**
* Loads the class with the specified <a href="#name">binary name</a>. The
* default implementation of this method searches for classes in the
* following order:
*
* <ol>
*
* <li><p> Invoke {@link #findLoadedClass(String)} to check if the class
* has already been loaded. </p></li>
*
* <li><p> Invoke the {@link #loadClass(String) <tt>loadClass</tt>} method
* on the parent class loader. If the parent is <tt>null</tt> the class
* loader built-in to the virtual machine is used, instead. </p></li>
*
* <li><p> Invoke the {@link #findClass(String)} method to find the
* class. </p></li>
*
* </ol>
*
* <p> If the class was found using the above steps, and the
* <tt>resolve</tt> flag is true, this method will then invoke the {@link
* #resolveClass(Class)} method on the resulting <tt>Class</tt> object.
*
* <p> Subclasses of <tt>ClassLoader</tt> are encouraged to override {@link
* #findClass(String)}, rather than this method. </p>
*
* <p> Unless overridden, this method synchronizes on the result of
* {@link #getClassLoadingLock <tt>getClassLoadingLock</tt>} method
* during the entire class loading process.
*
* @param name
* The <a href="#name">binary name</a> of the class
*
* @param resolve
* If <tt>true</tt> then resolve the class
*
* @return The resulting <tt>Class</tt> object
*
* @throws ClassNotFoundException
* If the class could not be found
*
*
* 加載指定的<a href="#name">二進制名</a>的類
* 此方法查找class的默認實現有有以下幾點:
* 1、調用findLoadedClass(String)檢查該Class是否已加載
* 2、調用父類加載器的loadClass(String)方法;如果父類加載器爲null,使用虛擬機內置的loader
* 3、調用findClass(String)方法去查找該Class
*
* 如果使用上述步驟找到該Class,且resolve是true,則調用resolveClass(Class),將結果返回;
* ClassLoader的子類鼓勵重寫findClass(String),而不是這個方法
*
* 除非被重寫,否則此方法在整個類加載過程中會對結果進行同步getClassLoadingLock
*
*
*/
protected Class<?> loadClass(String name, boolean resolve)
throws ClassNotFoundException
{
/**
* 除非被重寫,否則此方法在整個類加載過程中會對結果進行同步getClassLoadingLock
*/
synchronized (getClassLoadingLock(name)) {
// First, check if the class has already been loaded(第一,檢查該Class是否已加載)
Class<?> c = findLoadedClass(name);
if (c == null) {
long t0 = System.nanoTime();
try {
if (parent != null) {
/**
* 調用父類加載器的loadClass(String)方法
*/
c = parent.loadClass(name, false);
} else {
/**
* 如果父類加載器爲null,使用虛擬機內置的loader
* (BootstrapClassLoader,JVM實現,底層是native方法)
*/
c = findBootstrapClassOrNull(name);
}
} catch (ClassNotFoundException e) {
// ClassNotFoundException thrown if class not found
// from the non-null parent class loader
}
/**
* 以上步驟沒找到class的話
* 調用findClass(String)方法去查找該Class
*/
if (c == null) {
// If still not found, then invoke findClass in order
// to find the class.
long t1 = System.nanoTime();
c = findClass(name);
// this is the defining class loader; record the stats
sun.misc.PerfCounter.getParentDelegationTime().addTime(t1 - t0);
sun.misc.PerfCounter.getFindClassTime().addElapsedTimeFrom(t1);
sun.misc.PerfCounter.getFindClasses().increment();
}
}
if (resolve) {
// JVM實現,底層是native方法,如果c爲null會拋NullPointException異常
resolveClass(c);
}
return c;
}
}
/**
* Links the specified class. This (misleadingly named) method may be
* used by a class loader to link a class. If the class <tt>c</tt> has
* already been linked, then this method simply returns. Otherwise, the
* class is linked as described in the "Execution" chapter of
* <cite>The Java™ Language Specification</cite>.
*
* @param c
* The class to link
*
* @throws NullPointerException
* If <tt>c</tt> is <tt>null</tt>.
*
* @see #defineClass(String, byte[], int, int)
*
*
* 鏈接指定的類。這個(容易引起誤解的命名)方法可能是被類加載器用來鏈接類的。如果類c已鏈接,則此方法直接返回。否則,進行鏈接
*/
protected final void resolveClass(Class<?> c) {
// native方法,java源碼中方法以0結尾的一般都是native方法(例如Thread類的start()方法對應的start0()方法),需要JVM去調用C/C++去執行
resolveClass0(c);
}
/**
* Finds the class with the specified <a href="#name">binary name</a>.
* This method should be overridden by class loader implementations that
* follow the delegation model for loading classes, and will be invoked by
* the {@link #loadClass <tt>loadClass</tt>} method after checking the
* parent class loader for the requested class. The default implementation
* throws a <tt>ClassNotFoundException</tt>.
*
* @param name
* The <a href="#name">binary name</a> of the class
*
* @return The resulting <tt>Class</tt> object
*
* @throws ClassNotFoundException
* If the class could not be found
*
* @since 1.2
*
* 加載指定的<a href="#name">二進制名</a>的類
* 類加載器實現應該重寫此方法使用委託模型加載類,
* 將在loadClass(String name, boolean resolve)方法檢查父類加載後調用該該方法
* 默認實現拋出一個ClassNotFoundException異常
*/
protected Class<?> findClass(String name) throws ClassNotFoundException {
throw new ClassNotFoundException(name);
}
如果需要實現自定義的ClassLoader,可以通過重寫以上兩個方法來實現。從源碼中也可以看出,通常推薦重寫findClass()方法,而不是loadClass()方法。
從源碼中可以看出,重寫findClass()方法可以避免覆蓋默認類加載器的父類委託、緩存機制兩種策略;如果重寫loadClass()方法,實現邏輯更復雜。
我們來看看ClassLoader的源碼:
/**
* Converts an array of bytes into an instance of class <tt>Class</tt>,
* with an optional <tt>ProtectionDomain</tt>. If the domain is
* <tt>null</tt>, then a default domain will be assigned to the class as
* specified in the documentation for {@link #defineClass(String, byte[],
* int, int)}. Before the class can be used it must be resolved.
*
* 將字節數組轉換爲Class實例,
* *帶有一個可選的<tt>ProtectionDomain</tt>。如果定義域是null,則將一個默認域賦給該class,
* 該默認域需要在defineClass(String, byte[],int, int)文檔中指定。在使用Class之前,必須解析
*
* <p> The first class defined in a package determines the exact set of
* certificates that all subsequent classes defined in that package must
* contain. The set of certificates for a class is obtained from the
* {@link java.security.CodeSource <tt>CodeSource</tt>} within the
* <tt>ProtectionDomain</tt> of the class. Any classes added to that
* package must contain the same set of certificates or a
* <tt>SecurityException</tt> will be thrown. Note that if
* <tt>name</tt> is <tt>null</tt>, this check is not performed.
* You should always pass in the <a href="#name">binary name</a> of the
* class you are defining as well as the bytes. This ensures that the
* class you are defining is indeed the class you think it is.
*
* 作爲限定包中定義的第一個類,該包中定義的所有後續類必須包含精確的證書。
* 類的證書集從ProtectionDomain內的java.security.CodeSource 的CodeSource()中.
* 任何Class都可以添加到該包中必須包含同一套證書或者會拋SecurityException異常。
* 注意,如果name爲null,此檢查不執行。您應該始終傳入<a href="#name">二進制名</a>
* 類和字節一起定義。這確保了你定義的類確實是你認爲的類。
*
* <p> The specified <tt>name</tt> cannot begin with "<tt>java.</tt>", since
* all classes in the "<tt>java.*</tt> packages can only be defined by the
* bootstrap class loader. If <tt>name</tt> is not <tt>null</tt>, it
* must be equal to the <a href="#name">binary name</a> of the class
* specified by the byte array "<tt>b</tt>", otherwise a {@link
* NoClassDefFoundError <tt>NoClassDefFoundError</tt>} will be thrown. </p>
*
*指定的name不能以java.開頭,以java.開頭的Class只能由根類加載器加載。
* 如果name不爲null,則必須等於由字節數組b指定類的二進制名,否則拋出oClassDefFoundError錯誤
*
*
* @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>.
* 該數組的範圍爲[off,off+len-1]
*
* @param off
* The start offset in <tt>b</tt> of the class data
*
* @param len
* The length of the class data
*
* @param protectionDomain
* The ProtectionDomain of the class
*
* @return The <tt>Class</tt> object created from the data,
* and optional <tt>ProtectionDomain</tt>.
*
* @throws ClassFormatError
* If the data did not contain a valid class
*
* @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>
*
* @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, or if <tt>name</tt> begins with
* "<tt>java.</tt>".
*/
protected final Class<?> defineClass(String name, byte[] b, int off, int len,
ProtectionDomain protectionDomain)
throws ClassFormatError
{
protectionDomain = preDefineClass(name, protectionDomain);
String source = defineClassSourceLocation(protectionDomain);
Class<?> c = defineClass1(name, b, off, len, protectionDomain, source);
postDefineClass(c, protectionDomain);
return c;
}
在ClassLoader裏還有一個核心方法Class<?> defineClass(String name, byte[] b, int off, int len),該方法負責將指定類的字節碼文件(即Class文件,如Hello.class)讀入字節數組byte[] b中,並把它轉換爲Class對象,該字節碼可以來源於文件、網絡等。
defineClass()方法管理JVM的許多複雜實現,它負責將字節碼分析成運行時數據結構,並校驗有效。該方法時final類型,無法重寫。
除此之外,ClassLoader裏還包含一些普通方法:
- findSystemClass(String name): 從本地文件系統裝入文件,它在本地文件系統中尋找類文件,如果存在,就是要defineClass()方法將原始字節轉換成Class對象,將文件轉換成類。
/**
* Finds a class with the specified <a href="#name">binary name</a>,
* loading it if necessary.
*
* <p> This method loads the class through the system class loader (see
* {@link #getSystemClassLoader()}). The <tt>Class</tt> object returned
* might have more than one <tt>ClassLoader</tt> associated with it.
* Subclasses of <tt>ClassLoader</tt> need not usually invoke this method,
* because most class loaders need to override just {@link
* #findClass(String)}. </p>
*
* @param name
* The <a href="#name">binary name</a> of the class
*
* @return The <tt>Class</tt> object for the specified <tt>name</tt>
*
* @throws ClassNotFoundException
* If the class could not be found
*
* @see #ClassLoader(ClassLoader)
* @see #getParent()
*/
protected final Class<?> findSystemClass(String name)
throws ClassNotFoundException
{
ClassLoader system = getSystemClassLoader();
if (system == null) {
if (!checkName(name))
throw new ClassNotFoundException(name);
Class<?> cls = findBootstrapClass(name);
if (cls == null) {
throw new ClassNotFoundException(name);
}
return cls;
}
return system.loadClass(name);
}
- static getSystemClassLoader(): 這是一個靜態方法
/**
* Find a resource of the specified name from the search path used to load
* classes. This method locates the resource through the system class
* loader (see {@link #getSystemClassLoader()}).
*
* @param name
* The resource name
*
* @return A {@link java.net.URL <tt>URL</tt>} object for reading the
* resource, or <tt>null</tt> if the resource could not be found
*
* @since 1.1
*/
public static URL getSystemResource(String name) {
ClassLoader system = getSystemClassLoader();
if (system == null) {
return getBootstrapResource(name);
}
return system.getResource(name);
}
- getParent():獲取該類的父類加載器
/**
* Returns the parent class loader for delegation. Some implementations may
* use <tt>null</tt> to represent the bootstrap class loader. This method
* will return <tt>null</tt> in such implementations if this class loader's
* parent is the bootstrap class loader.
*
* <p> If a security manager is present, and the invoker's class loader is
* not <tt>null</tt> and is not an ancestor of this class loader, then this
* method invokes the security manager's {@link
* SecurityManager#checkPermission(java.security.Permission)
* <tt>checkPermission</tt>} method with a {@link
* RuntimePermission#RuntimePermission(String)
* <tt>RuntimePermission("getClassLoader")</tt>} permission to verify
* access to the parent class loader is permitted. If not, a
* <tt>SecurityException</tt> will be thrown. </p>
*
* @return The parent <tt>ClassLoader</tt>
*
* @throws SecurityException
* If a security manager exists and its <tt>checkPermission</tt>
* method doesn't allow access to this class loader's parent class
* loader.
*
* @since 1.2
*/
@CallerSensitive
public final ClassLoader getParent() {
if (parent == null)
return null;
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
// Check access to the parent class loader
// If the caller's class loader is same as this class loader,
// permission check is performed.
checkClassLoaderPermission(parent, Reflection.getCallerClass());
}
return parent;
}
- resolveClass(Class<?> c): 鏈接指定的類。類加載器可以使用此方法來鏈接類c
- findLoadedClass(String name): 如果此Java虛擬機已經加載了名爲name的類,則直接返回該類對應的Class實例,否則返回null。該方法是Java類加載緩存機制的體現。
/**
* Returns the class with the given <a href="#name">binary name</a> if this
* loader has been recorded by the Java virtual machine as an initiating
* loader of a class with that <a href="#name">binary name</a>. Otherwise
* <tt>null</tt> is returned.
*
* @param name
* The <a href="#name">binary name</a> of the class
*
* @return The <tt>Class</tt> object, or <tt>null</tt> if the class has
* not been loaded
*
* @since 1.1
*/
protected final Class<?> findLoadedClass(String name) {
if (!checkName(name))
return null;
return findLoadedClass0(name);
}
下面自定義類加載器,該ClassLoader通過重寫findClass()方法來實現自定義的類加載機制。這個ClassLoader可以在類加載之前先編譯該類的源文件,從而實現運行Java之前先編譯該程序的目標,這樣即可通過該ClassLoader直接運行Java源文件。
// package cn.crazy.load;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Method;
/**
* @ProjectName: Java
* @Package: cn.crazy.load
* @ClassName: MyClassLoader
* @Author: zhangli
* @Description: 自定義類加載器
* @Date: 2020/5/30 16:12
* @Version: 1.0
*/
public class MyClassLoader extends ClassLoader{
/**
* 讀取一個文件的內容
* @param fileName
* @return
* @throws Exception
*/
private byte[] getBytes(String fileName) throws Exception{
File file = new File(fileName);
long length = file.length();
byte[] buffer = new byte[(int) length];
FileInputStream inputStream = new FileInputStream(file);
/**
* 一次性讀取Class文件的全部二進制數據
*/
int len = inputStream.read(buffer);
if(len != length){
throw new IOException("無法讀取全部文件[讀取長度:" + len + ", 文件長度:" + length + "]");
}
return buffer;
}
/**
* 編譯指定的Java文件
* @param javaFile
* @return
* @throws Exception
*/
private boolean compile(String javaFile) throws Exception{
System.out.println("MyClassLoader正在編譯"+ javaFile + "……");
/**
* 調用系統的javac命令
*/
Process process = Runtime.getRuntime().exec("javac -encoding UTF-8 " + javaFile);
System.out.println("調用系統的javac命令");
try {
/**
* 其他線程都等待這個線程完成
*/
process.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("其他線程都等待這個線程完成");
/**
* 獲取線程的退出值(0表示正常終止)
*/
int value = process.exitValue();
/**
* 編譯是否成功
*/
if(value == 0){
System.out.println("編譯成功");
}
return value == 0;
}
/**
* 重寫ClassLoader的findClass()方法
* @param name
* @return
* @throws ClassNotFoundException
*/
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
Class<?> clazz = null;
/**
* 將包路徑中的.替換成/
*/
String filePath = name.replace(".", "/");
System.out.println("filePath = " + filePath);
String javaFileName = filePath + ".java";
String classFileName = filePath + ".class";
/**
* 加載文件
*/
File javaFile = new File(javaFileName);
File classFile = new File(classFileName);
/**
* 當指定java源文件存在,且Class文件不存在
* 或者
* java源文件的修改時間比Class文件的修改時間更晚,需要重新編譯
*/
if((javaFile.exists() && !classFile.exists()) || (javaFile.lastModified() > classFile.lastModified())){
try {
/**
* 如果編譯失敗或者該Class文件不存在,拋出ClassNotFoundException
*/
if(!compile(javaFileName) || !classFile.exists()){
throw new ClassNotFoundException("ClassNotFoundException:" + javaFileName);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 如果Class文件存在,將該文件轉換成Class對象
*/
if(classFile.exists()){
try {
// 將Class文件的二進制數據轉換成數組
byte[] bytes = getBytes(classFileName);
/**
* 調用ClassLoader的defineClass()方法將二進制數據轉換成Class對象
*/
clazz = defineClass(name, bytes, 0, bytes.length);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 加載失敗,拋出ClassNotFoundException
*/
if(clazz == null){
throw new ClassNotFoundException(name);
}
return clazz;
}
public static void main(String[] args) throws Exception {
/**
* 如果運行該程序時沒有參數,即沒有目標類
*/
if(args.length < 1){
System.out.println("缺少目標類,請按如下格式輸入Java源文件: ");
System.out.println("java MyClassLoader ClassName");
}
/**
* cn.crazy.load.MyClassLoader cn.crazy.load.ClassLoadingTest
* src/cn/crazy/load/MyClassLoader.java
*
*
*/
/**
* 第一個參數是需要運行的類
*/
String runClass = args[0];
/**
* 剩下的參數作爲運行目標類時的參數
*/
String[] runArgs = new String[args.length -1];
System.arraycopy(args, 1, runArgs, 0, runArgs.length);
MyClassLoader myClassLoader = new MyClassLoader();
Class<?> clazz = myClassLoader.loadClass(runClass);
/**
* 獲取需要運行的類的main()方法
*/
Method main = clazz.getMethod("main", (new String[0]).getClass());
Object[] argsArr = {runArgs};
main.invoke(null,argsArr);
}
}
// package cn.crazy.load;
/**
* @ProjectName: Java
* @Package: cn.crazy.load
* @ClassName: ClassLoadingTest
* @Author: zhangli
* @Description: 類加載測試
* @Date: 2020/5/31 16:56
* @Version: 1.0
*/
public class ClassLoadingTest {
public static void main(String[] args) {
for(String arg : args){
System.out.println("運行參數:" + arg);
}
}
}
運行:cmd命令要進入MyClassLoader.java路徑下,記得將包名註釋掉,否則會報“無法加載主類”的錯誤。
MyClassLoader.java是要進行編譯的,編譯時最好指定編碼格式,預防中文亂碼錯誤。
cmd輸入:
javac -encoding UTF-8 MyClassLoader.java
java MyClassLoader ClassLoadingTest zhangli test 測試
從上面的運行結果可以看出無須編譯ClassLoadingTest.java,直接通過java MyClassLoader ClassLoadingTest命令運行即可。
實際上,使用自定義的類加載器可以實現更多複雜的功能,比如:
- 執行代碼前自動驗證數字簽名
- 根據用戶提供的密碼解密代碼,從而實現代碼混淆器來避免反編譯*.class文件
- 根據用戶需求動態的加載類
- 根據應用需求把其他數據以字節碼的方式加載到應用中
URLClassLoader類
Java爲ClassLoader提供了一個URLClassLoader實現類。該類也是系統類加載器和擴展類加載器的父類(此處的父類,就是指類與類之間的繼承關係)。URLClassLoader功能比較強大,它既可以從本地文件系統獲取二進制文件來加載類,也可以從遠程主機獲取二進制文件類加載類。
在應用程序中可以直接使用URLClassLoader加載類,URLClassLoader類提供瞭如下兩個構造器。
- URLClassLoader(URL[] urls): 使用 默認的父類類加載器創建一個ClassLoader對象 ,該對象 從urls所指定的系統路徑來查詢並加載類
- URLClassLoader(URL[] urls, ClassLoader parent): 使用指定 的父類加載器創建一個ClassLoader對象,其他功能與前一個構造器相同。
一旦得到了URLClassLoader對象之後,就可以調用該對象的loadClass()方法類加載指定類。
下面程序 示範瞭如何直接從文件系統中加載MySQL驅動,並使用該驅動來獲取數據庫連接。通過這種方式來獲取數據庫連接,無須將MySQL驅動添加到CLASSPATH環境變量中。
public class URLClassLoaderTest {
/**
* sql連接對象
*/
private static Connection connection;
/**
* 獲取sql連接對象
*/
public static Connection getConnection(String url, String username, String password) throws Exception{
if(connection == null){
/**
* mysql-connector-java-5.1.37.jar放在當前java文件路徑下
* file: 表示本地文件加載
*/
URL[] urls = {new URL("file:mysql-connector-java-5.1.37.jar")};
URLClassLoader loader = new URLClassLoader(urls);
Driver driver = (Driver) loader.loadClass("com.mysql.jdbc.Driver").newInstance();
/**
* 創建一個設置jdbc連接的Properties對象
*/
Properties properties = new Properties();
properties.setProperty("user", username);
properties.setProperty("password", password);
/**
* 調用Driver對象的connect方法取得數據庫連接
*/
connection = driver.connect(url, properties);
}
return connection;
}
public static void main(String[] args) throws Exception{
Connection connection = getConnection("jdbc:mysql://localhost:3306/mysql", "root", "123456");
/**
* 拿到connection進行數據庫操作
* ……
*/
}
}
上面的程序創建了一個URLClassLoader對象,該對象使用默認父類加載器,該類加載器的類加載路徑是當前路徑下的mysql-connector-java-5.1.37.jar文件。創建URLClassLoader時傳入一個URL數組參數,該ClassLoader就可以從該URL數組中加載指定類,這裏的URL以file:爲前綴,表明從本地文件系統加載;可以以http:爲前綴,表明從互聯網通過HTTP訪問加載;可以以ftp:爲前綴,表明從互聯網通過FTP訪問來加載……功能非常強大。