在 Java 的反射中,Class.forName 和 ClassLoader 的区别

前言

最近在面试过程当中有被问到,在Java反射中Class.forName()加载类和使用ClassLoader加载类的区别。当时没有想出来后来本身研究了一下就写下来记录一下。html

解释

在java中Class.forName()和ClassLoader均可以对类进行加载。ClassLoader就是遵循双亲委派模型最终调用启动类加载器的类加载器,实现的功能是“经过一个类的全限定名来获取描述此类的二进制字节流”,获取到二进制流后放到JVM中。Class.forName()方法实际上也是调用的CLassLoader来实现的。java

Class.forName(String className);这个方法的源码是 `` 最后调用的方法是forName0这个方法,在这个forName0方法中的第二个参数被默认设置为了true,这个参数表明是否对加载的类进行初始化,设置为true时会类进行初始化,表明会执行类中的静态代码块,以及对静态变量的赋值等操做。面试

也能够调用Class.forName(String name, boolean initialize,ClassLoader loader)方法来手动选择在加载类的时候是否要对类进行初始化。Class.forName(String name, boolean initialize,ClassLoader loader)的源码以下:sql

   /**
     * Returns the {@code Class} object associated with the class or
     * interface with the given string name.  Invoking this method is
     * equivalent to:
     *
     * <blockquote>
     *  {@code Class.forName(className, true, currentLoader)}
     * </blockquote>
     *
     * where {@code currentLoader} denotes the defining class loader of
     * the current class.
     *
     * <p> For example, the following code fragment returns the
     * runtime {@code Class} descriptor for the class named
     * {@code java.lang.Thread}:
     *
     * <blockquote>
     *   {@code Class t = Class.forName("java.lang.Thread")}
     * </blockquote>
     * <p>
     * A call to {@code forName("X")} causes the class named
     * {@code X} to be initialized.
     *
     * @param      className   the fully qualified name of the desired class.
     * @return     the {@code Class} object for the class with the
     *             specified name.
     * @exception LinkageError if the linkage fails
     * @exception ExceptionInInitializerError if the initialization provoked
     *            by this method fails
     * @exception ClassNotFoundException if the class cannot be located
     */
   @CallerSensitive
   public static Class<?> forName(String className)  throws ClassNotFoundException {
       Class<?> caller = Reflection.getCallerClass();
       return forName0(className, true, ClassLoader.getClassLoader(caller), 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();
        }
 
    }
}

运行结果:ui

执行了静态代码块
执行了静态方法
#########分割符(上面是Class.forName的加载过程,下面是ClassLoader的加载过程)##########

根据运行结果得出Class.forName加载类是将类进了初始化,而ClassLoader的loadClass并无对类进行初始化,只是把类加载到了虚拟机中。this

应用场景

在咱们熟悉的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()的缘由了。

好了,今天就写到这了,最近在面试,遇到了不少问题,也学习了很多,虽然很累,可是也让人成长了很多,毕竟面试就是一个脱皮的过程,会遇到各类企业各类面试官各类问题,各类场景。给本身加油吧,找一个最少能让本身干个几年的公司,别老是让我遇到工做了没多久公司就垮掉的这种就好了。要不我也很无奈啊。

原文:http://www.importnew.com/29389.html

相关文章
相关标签/搜索