ClassLoader源码分析

本文详细探讨了Java ClassLoader的工作原理,包括层次结构、显式加载类的方式、loadClass()和findClass()的区别,以及自定义加载器的实现。特别强调了在自定义ClassLoader时,如何覆盖findClass()和loadClass()方法以改变加载路径和机制。同时,文章还提到了类的热部署策略和一些不可覆盖的final方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

层次结构和类图

ClassLoader层次结构:

 
 
 
UML类图:
 

 
  • sun.misc.Launcher.ExtClassLoader
  • sun.misc.Launcher.AppClassLoader
 

显式加载类

在代码中显式加载某个类,有三种方法:
  1. this.getClass().getClassLoader().loadClass()
  2. Class.forName()
  3. MyClassLoader.findClass()

ClassLoader.loadClass()

ClassLoader.loadClass()的加载步骤为:
  1. 调用 findLoadedClass(String) 来检查是否已经加载类。
  2. 在父类加载器上调用 loadClass 方法。如果父类加载器为 null,则使用虚拟机的内置类加载器。
  3. 调用 findClass(String) 方法查找类。

 

 
     public Class<?> loadClass(String name) throws ClassNotFoundException {
        return loadClass(name, false);
    }
    /**
     * 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:
     *
     * <p><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> 
     */
    protected synchronized Class<?> loadClass(String name, boolean resolve)
    throws ClassNotFoundException
    {
    // First, check if the class has already been loaded
    Class c = findLoadedClass(name);
    if (c == null) {
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值