ClassLoader源码分析

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

层次结构和类图

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);
    
Spring动态代理主要是通过JDK动态代理和CGLIB动态代理两种方式实现的。其中,JDK动态代理是基于接口的代理,而CGLIB动态代理则是基于类的代理。 在使用JDK动态代理时,Spring会根据目标对象实现的接口来创建代理对象。具体实现过程如下: 1. 创建一个实现InvocationHandler接口的代理处理器对象,该对象负责实际的代理操作。 2. 调用Proxy类的静态方法newProxyInstance()来创建代理对象。该方法需要传入三个参数:ClassLoader对象、目标对象实现的接口列表以及代理处理器对象。 3. 当调用代理对象的方法时,实际上是调用了InvocationHandler接口的invoke()方法,该方法会根据传入的Method对象和参数列表来执行目标对象的方法。 而在使用CGLIB动态代理时,Spring会通过ASM字节码框架来生成一个子类,并重写其中的方法来实现代理。具体实现过程如下: 1. 创建一个Enhancer对象,该对象负责生成子类。 2. 设置父类和回调函数。父类即为目标对象,回调函数即为MethodInterceptor接口的实现类,该类负责实际的代理操作。 3. 调用Enhancer对象的create()方法来创建代理对象。该方法会生成一个子类,并重写其中的方法来实现代理。 4. 当调用代理对象的方法时,实际上是调用了MethodInterceptor接口的intercept()方法,该方法会根据传入的Method对象和参数列表来执行目标对象的方法。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值