1. 程式人生 > >Java反射中Class.forName()載入類和使用ClassLoader載入類的區別

Java反射中Class.forName()載入類和使用ClassLoader載入類的區別

最近在面試過程中有被問到,在Java反射中Class.forName()載入類和使用ClassLoader載入類的區別。當時沒有想出來後來自己研究了一下就寫下來記錄一下。

解釋

在java中Class.forName()和ClassLoader都可以對類進行載入。ClassLoader就是遵循雙親委派模型最終呼叫啟動類載入器的類載入器,實現的功能是“通過一個類的全限定名來獲取描述此類的二進位制位元組流”,獲取到二進位制流後放到JVM中。Class.forName()方法實際上也是呼叫的CLassLoader來實現的。

Class.forName(String className);這個方法的原始碼是:

@CallerSensitive
    public static Class<?> forName(String className)
                throws ClassNotFoundException {
        Class<?> caller = Reflection.getCallerClass();
        return forName0(className, true, ClassLoader.getClassLoader(caller), caller);
    }

最後呼叫的方法是forName0這個方法,在這個forName0方法中的第二個引數被預設設定為了true,這個引數代表是否對載入的類進行初始化,設定為true時會類進行初始化,代表會執行類中的靜態程式碼塊,以及對靜態變數的賦值等操作。

也可以呼叫Class.forName(String name, boolean initialize,ClassLoader loader)方法來手動選擇在載入類的時候是否要對類進行初始化。Class.forName(String name, boolean initialize,ClassLoader loader)的原始碼如下:

/* @param name       fully qualified name of the desired class
     * @param initialize if {@code true} the class will be initialized.
     *                   See Section 12.4 of <em>The Java Language Specification</em>.
     * @param loader     class loader from which the class must be loaded
     * @return           class object representing the desired class
     *
     * @exception LinkageError if the linkage fails
     * @exception ExceptionInInitializerError if the initialization provoked
     *            by this method fails
     * @exception ClassNotFoundException if the class cannot be located by
     *            the specified class loader
     *
     * @see       java.lang.Class#forName(String)
     * @see       java.lang.ClassLoader
     * @since     1.2
     */
    @CallerSensitive
    public static Class<?> forName(String name, boolean initialize,
                                   ClassLoader loader)
        throws ClassNotFoundException
    {
        Class<?> caller = null;
        SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            // Reflective call to get caller class is only needed if a security manager
            // is present.  Avoid the overhead of making this call otherwise.
            caller = Reflection.getCallerClass();
            if (sun.misc.VM.isSystemDomainLoader(loader)) {
                ClassLoader ccl = ClassLoader.getClassLoader(caller);
                if (!sun.misc.VM.isSystemDomainLoader(ccl)) {
                    sm.checkPermission(
                        SecurityConstants.GET_CLASSLOADER_PERMISSION);
                }
            }
        }
        return forName0(name, initialize, loader, caller);
    }

原始碼中的註釋只摘取了一部分,其中對引數initialize的描述是:if {@code true} the class will be initialized.意思就是說:如果引數為true,則載入的類將會被初始化。

舉例

下面還是舉例來說明結果吧:

一個含有靜態程式碼塊、靜態變數、賦值給靜態變數的靜態方法的類

public class ClassForName {

    //靜態程式碼塊
    static {
        System.out.println("執行了靜態程式碼塊");
    }
    //靜態變數
    private static String staticFiled = staticMethod();

    //賦值靜態變數的靜態方法
    public static String staticMethod(){
        System.out.println("執行了靜態方法");
        return "給靜態欄位賦值了";
    }
}

測試方法:

public class MyTest {
    @Test
    public void test44(){

        try {
            Class.forName("com.test.mytest.ClassForName");
            System.out.println("#########分割符(上面是Class.forName的載入過程,下面是ClassLoader的載入過程)##########");
            ClassLoader.getSystemClassLoader().loadClass("com.test.mytest.ClassForName");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

    }
}

執行結果:

執行了靜態程式碼塊
執行了靜態方法
#########分割符(上面是Class.forName的載入過程,下面是ClassLoader的載入過程)##########

根據執行結果得出Class.forName載入類是將類進了初始化,而ClassLoader的loadClass並沒有對類進行初始化,只是把類載入到了虛擬機器中。

應用場景

在我們熟悉的Spring框架中的IOC的實現就是使用的ClassLoader。

而在我們使用JDBC時通常是使用Class.forName()方法來載入資料庫連線驅動。這是因為在JDBC規範中明確要求Driver(資料庫驅動)類必須向DriverManager註冊自己。

以MySQL的驅動為例解釋:

public class Driver extends NonRegisteringDriver implements java.sql.Driver {  
    // ~ Static fields/initializers  
    // ---------------------------------------------  

    //  
    // Register ourselves with the DriverManager  
    //  
    static {  
        try {  
            java.sql.DriverManager.registerDriver(new Driver());  
        } catch (SQLException E) {  
            throw new RuntimeException("Can't register driver!");  
        }  
    }  

    // ~ Constructors  
    // -----------------------------------------------------------  

    /** 
     * Construct a new driver and register it with DriverManager 
     *  
     * @throws SQLException 
     *             if a database error occurs. 
     */  
    public Driver() throws SQLException {  
        // Required for Class.forName().newInstance()  
    }  
}

我們看到Driver註冊到DriverManager中的操作寫在了靜態程式碼塊中,這就是為什麼在寫JDBC時使用Class.forName()的原因了。