点击上方 Java后端,选择 设为星标
优质文章,及时送达
前言
ClassLoader
加载类的区别。当时没有想出来后来自己研究了一下就写下来记录一下。
解释
ClassLoader
都可以对类进行加载。ClassLoader就是遵循双亲委派模型最终调用启动类加载器的类加载器,实现的功能是“通过一个类的全限定名来获取描述此类的二进制字节流”,获取到二进制流后放到
JVM
中。Class.forName()方法实际上也是调用的
ClassLoader
来实现的。
   
   
   
 
    
    
    @CallerSensitive
 
    
    
    
 
    
    
    public 
 
    
    
    static Class<?> forName(String className)
 
    
    
    
            
 
    
    
    throws ClassNotFoundException {
 
    
    
    
    Class<?> caller = Reflection.getCallerClass();
 
    
    
    
    
 
    
    
    return forName0(className, 
 
    
    
    true, ClassLoader.getClassLoader(caller), caller);
 
    
    
    
}
 
    
    
    
   
   
    
   
   
   
 
    
    
    /* @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);
 
    
    
    
}
 
    
    
    
   
   
    
举例
   
   
   
 
    
    
    public 
 
    
    
    class 
 
    
    
    ClassForName {
 
    
    
    
 
    
    
    
    
 
    
    
    //静态代码块
 
    
    
    
    
 
    
    
    static {
 
    
    
    
        System.
 
    
    
    out.println(
 
    
    
    "执行了静态代码块");
 
    
    
    
    }
 
    
    
    
    
 
    
    
    //静态变量
 
    
    
    
    
 
    
    
    private 
 
    
    
    static String staticFiled = staticMethod();
 
    
    
    
 
    
    
    
    
 
    
    
    //赋值静态变量的静态方法
 
    
    
    
    
 
    
    
    public static String staticMethod(){
 
    
    
    
        System.
 
    
    
    out.println(
 
    
    
    "执行了静态方法");
 
    
    
    
        
 
    
    
    return 
 
    
    
    "给静态字段赋值了";
 
    
    
    
    }
 
    
    
    
 
    
    
    
}
 
    
    
    
   
   
    
   
   
   
    
    
    
 @
 
    
    
    Test
public void test45(){
 
    
    
    
    
 
    
    
    try {
 
    
    
    
        ClassLoader.getSystemClassLoader().loadClass(
 
    
    
    "com.eurekaclient2.client2.ClassForName");
 
    
    
    
        System.
 
    
    
    out.println(
 
    
    
    "#########-------------结束符------------##########");
 
    
    
    
    } 
 
    
    
    catch (ClassNotFoundException e) {
 
    
    
    
        e.printStackTrace();
 
    
    
    
    }
 
    
    
    
}
 
    
    
    
   
   
    
   
   
   
    
    
    
 执行了静态代码块执行了静态方法
 
    
    
    #########-------------结束符------------##########  
 
    
    
    
   
   
    
   
   
   
    
    
    
 @
 
    
    
    Test
public void test45(){
 
    
    
    
    
 
    
    
    try {
 
    
    
    
        ClassLoader.getSystemClassLoader().loadClass(
 
    
    
    "com.eurekaclient2.client2.ClassForName");
 
    
    
    
        System.
 
    
    
    out.println(
 
    
    
    "#########-------------结束符------------##########");
 
    
    
    
    } 
 
    
    
    catch (ClassNotFoundException e) {
 
    
    
    
        e.printStackTrace();
 
    
    
    
    }
 
    
    
    
}
 
    
    
    
   
   
    
#########-------------结束符------------##########
根据运行结果得出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()的原因了。
好了,今天就写到这了,最近在面试,遇到了很多问题,也学习了不少,虽然很累,但是也让人成长了不少,毕竟面试就是一个脱皮的过程,会遇到各种企业各种面试官各种问题,各种场景。
如果看到这里,说明你喜欢这篇文章,请 转发、点赞。同时 标星(置顶)本公众号可以第一时间接受到博文推送。
推荐阅读
1. 今天我们来聊一聊 Spring 中的线程安全性
2. 强烈推荐 16 款 IDEA 插件
3. 30 分钟学会如何使用 Shiro
4. Spring Boot+Redis实现接口自动幂等

《Java技术栈学习手册》
,覆盖了Java技术、面试题精选、Spring全家桶、Nginx、SSM、微服务、数据库、数据结构、架构等等。
获取方式:点“ 在看,关注公众号 Java后端 并回复 777 领取,更多内容陆续奉上。
喜欢文章,点个在看 
本文分享自微信公众号 - Java后端(web_resource)。
如有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。
