Class.forName 和 ClassLoader 到底有啥区别?

简介: 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 "给静态字段赋值了";
    }
}

使用Class.forName()的测试方法:

@Test
public void test45(){
    try {
        ClassLoader.getSystemClassLoader().loadClass("com.eurekaclient2.client2.ClassForName");
        System.out.println("#########-------------结束符------------##########");
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
}

运行结果:

执行了静态代码块执行了静态方法#########-------------结束符------------##########  

使用ClassLoader的测试方法:

@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()的原因了。


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


等找到工作后,会总结自己面经的。


作者:纪莫 https://www.cnblogs.com/jimoer/p/9185662.html


关注Java技术栈微信公众号,栈长将继续分享好玩的 Java 技术,公众号第一时间推送,在公众号后台回复:Java,可以获取历史 Java 教程,都是干货。


推荐去我的博客阅读更多:


1.Java JVM、集合、多线程、新特性系列教程


2.Spring MVC、Spring Boot、Spring Cloud 系列教程


3.Maven、Git、Eclipse、Intellij IDEA 系列工具教程


4.Java、后端、架构、阿里巴巴等大厂最新面试题


生活很美好,明天见~


相关文章
|
机器学习/深度学习 人工智能 搜索推荐
协同过滤算法:个性化推荐的艺术与科学
协同过滤算法:个性化推荐的艺术与科学
协同过滤算法:个性化推荐的艺术与科学
|
8月前
|
机器学习/深度学习 人工智能 自然语言处理
人工智能在虚拟客服中的关键作用:提升交互体验与服务效率
人工智能在虚拟客服中的关键作用:提升交互体验与服务效率
483 90
|
11月前
|
NoSQL 测试技术
内存程序崩溃
【10月更文挑战第13天】
331 62
|
11月前
|
运维 监控 Cloud Native
运维之道:从基础到进阶的实战指南
【10月更文挑战第20天】 在数字化时代,运维作为保障系统稳定运行的重要环节,其重要性不言而喻。本文将带你深入探索运维的核心领域,从基础概念解析到进阶技能提升,通过一系列实用的技巧和策略,帮助你构建高效、可靠的运维体系,确保业务连续性和数据安全。
536 6
|
11月前
|
消息中间件 数据采集 数据库
小说爬虫-03 爬取章节的详细内容并保存 将章节URL推送至RabbitMQ Scrapy消费MQ 对数据进行爬取后写入SQLite
小说爬虫-03 爬取章节的详细内容并保存 将章节URL推送至RabbitMQ Scrapy消费MQ 对数据进行爬取后写入SQLite
161 1
|
12月前
|
存储 关系型数据库 MySQL
binlog、redolog、undo log底层原理及ACID特性实现分享
在数据库管理系统中,日志机制是确保数据一致性、完整性和可靠性的关键组件。MySQL数据库中的binlog、redolog和undolog作为其核心日志系统,各自扮演着不同但同样重要的角色。本文将深入探讨这三种日志的底层原理以及它们如何分别实现ACID(原子性、一致性、隔离性、持久性)特性的不同方面。
266 0
|
Docker 容器
docker 部署gitlab
docker 部署gitlab
186 0
|
机器学习/深度学习 人工智能 搜索推荐
未来互联网发展趋势分析与展望
当我们谈论互联网的未来,往往会聚焦于新技术的应用和发展趋势。然而,除了技术本身的创新,还有许多其他因素也将对未来互联网产生深远的影响。本文将探讨未来互联网发展的几个重要趋势,涉及人工智能、区块链、物联网等领域,并分析其可能带来的社会变革和商业机遇。
645 3
|
缓存 Linux
[cmake] ---- set_property
[cmake] ---- set_property
403 1
|
消息中间件 关系型数据库 MySQL
2021年最新Flink读写Kafka数据——Flink数据写入Kafka+从Kafka存入Mysql(二)
2021年最新Flink读写Kafka数据——Flink数据写入Kafka+从Kafka存入Mysql(二)
289 0