Cglib动态代理

上一篇我们学习了JDK 动态代理的实现逻辑,这里我们来学习一下Cglib 的实现逻辑。以方便对动态代理有一个全面的认识。

首先,我们来看一下生成代理类的时序图,对比起JDK的实现,它复杂了很多。

Cglib代理类时序图

整体看上去比较难以理解,那我们来看下这些类图,可能更加清晰些。

代理类生成类图

来看看入口类 Enhancer ,它继承自 AbstractClassGenerator ,而 AbstractClassGenerator 实现了 ClassGenerator 接口,ClassLoaderData 又是 AbstractClassGenerator 的内部类,哦,原来它们是一家的。既然知道了主体结构,那我们来看一下,核心的实现代码,整体逻辑与JDK基本一致生成类名,生成字节码对象,最后生成代理类实例。

protected Class generate(ClassLoaderData data) {
    Class gen;
    ...
    try {
        ClassLoader classLoader = data.getClassLoader();
        ...
        synchronized (classLoader) {
          // 生成类名
          String name = generateClassName(data.getUniqueNamePredicate());              
          data.reserveName(name);
          this.setClassName(name);
        }
        if (attemptLoad) {
            try {
                gen = classLoader.loadClass(getClassName());
                return gen;
            } catch (ClassNotFoundException e) {
                // ignore
            }
        }
        // 生成代理类字节码
        byte[] b = strategy.generate(this);
        String className = ClassNameReader.getClassName(new ClassReader(b));
        ProtectionDomain protectionDomain = getProtectionDomain();
        // 生成代理类字节码对象
        synchronized (classLoader) { // just in case
            if (protectionDomain == null) {
                gen = ReflectUtils.defineClass(className, b, classLoader);
            } else {
                gen = ReflectUtils.defineClass(className, b, classLoader, protectionDomain);
            }
        }
        return gen;
    } catch (RuntimeException e) {
        ...
    }
}

在上面的代码中没有生成实例对象的方法,它们是:

abstract protected Object firstInstance(Class type) throws Exception;
abstract protected Object nextInstance(Object instance) throws Exception;

具体的实现逻辑都在 Enhancer 里面。

好吧,上面列举了一堆,但还是没有看到代理类的真容,下面,我们将生成好的代理类class文件输出,反编译查看更具体的实现。

DebuggingClassWriter 里面有如下一段代码:

public static final String DEBUG_LOCATION_PROPERTY = "cglib.debugLocation";

static {
    debugLocation = System.getProperty(DEBUG_LOCATION_PROPERTY);
    if (debugLocation != null) {
        System.err.println("CGLIB debugging enabled, writing to '" + debugLocation + "'");
        try {
          Class clazz = Class.forName("org.objectweb.asm.util.TraceClassVisitor");
          traceCtor = clazz.getConstructor(new Class[]{ClassVisitor.class, PrintWriter.class});
        } catch (Throwable ignore) {
        }
    }
}

DEBUG_LOCATION_PROPERTY 可通过运行时的环境变量配置,用于指定代理类class文件的存放路径。

public static void main(String[] args) {
    String userDir = System.getProperty("user.dir");
    System.setProperty(DebuggingClassWriter.DEBUG_LOCATION_PROPERTY, userDir);
    Enhancer enhancer = new Enhancer();
    enhancer.setSuperclass(SystemMgrImpl.class);
    enhancer.setCallback(new SystemMgrTxnMethodInterceptor());
    SystemMgrImpl proxyInstance = (SystemMgrImpl) enhancer.create();
    System.out.println(proxyInstance.updateUser());
}

运行程序后,会在项目的根路径下生成class文件,如果不知道路径,在控制中也会输出具体的存放路径。会生成三个类,其中类名不带FastClass 的class文件就是最终的代理类。

这里,我们进行反编译,得到如下源码:

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.qchery.basics.design.pattern.proxy;

import java.lang.reflect.Method;
import net.sf.cglib.core.ReflectUtils;
import net.sf.cglib.proxy.Factory;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

public class SystemMgrImpl$$EnhancerByCGLIB$$3e3db737 extends SystemMgrImpl implements Factory {
    ...
    private MethodInterceptor CGLIB$CALLBACK_0;
    private static final Method CGLIB$updateUser$0$Method;
    private static final MethodProxy CGLIB$updateUser$0$Proxy;

    static {
        // 获取代理类Class字节码
        Class var0 = Class.forName("com.qchery.basics.design.pattern.proxy.SystemMgrImpl$$EnhancerByCGLIB$$3e3db737");
        // 获取目标类Class字节码
        Class var1 = Class.forName("com.qchery.basics.design.pattern.proxy.SystemMgrImpl");
        Method[] var10000 = ReflectUtils.findMethods(new String[]{"updateUser"}, var1.getDeclaredMethods());
        CGLIB$updateUser$0$Method = var10000[0];
        // 为代理方法创建MethodProxy
        CGLIB$updateUser$0$Proxy = MethodProxy.create(var1, var0, "()Ljava/lang/String;", "updateUser", "CGLIB$updateUser$0");
    }

    final String CGLIB$updateUser$0() {
        return super.updateUser();
    }

    public final String updateUser() {
        MethodInterceptor var10000 = this.CGLIB$CALLBACK_0;
        if (this.CGLIB$CALLBACK_0 == null) {
            CGLIB$BIND_CALLBACKS(this);
            var10000 = this.CGLIB$CALLBACK_0;
        }
        // 调用 MethodInterceptor
        return var10000 != null ? (String)var10000.intercept(this, CGLIB$updateUser$0$Method, CGLIB$emptyArgs, CGLIB$updateUser$0$Proxy) : super.updateUser();
    }

    ...
}

通过上面的代码,我们可以分析得出如下类图:

代理类实现类图

其中,代理类继承目标类,并为所有方法生成一个MethodProxy用于代理目标方法,在调用代理类的方法时,会委托MethodInterceptor调用intercept方法。因此,在实现MethodInterceptor 时,需要通过 proxy.invokeSuper(obj, args) 调用目标类的实现,如果调成了代理类的实现会形成无限递归。

注:目标类不可是final类,同时,必须包含无参的构造方法。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
CGLIB是一个强大的开源代码生成库,它可以在运行时扩展Java类和实现接口。CGLIB动态代理CGLIB库的一个重要特性,它通过生成目标类的子类来实现代理。 在CGLIB动态代理中,我们可以使用`MethodInterceptor`接口来定义代理逻辑。`MethodInterceptor`接口有一个`intercept`方法,该方法在目标方法被调用时被触发。在`intercept`方法中,我们可以编写自定义的逻辑来增强目标方法的功能。 下面是一个使用CGLIB动态代理的示例代码: ```java import net.sf.cglib.proxy.Enhancer; import net.sf.cglib.proxy.MethodInterceptor; import net.sf.cglib.proxy.MethodProxy; import java.lang.reflect.Method; public class CglibProxyExample implements MethodInterceptor { public Object createProxy(Object target) { Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(target.getClass()); enhancer.setCallback(this); return enhancer.create(); } @Override public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { // 在目标方法执行前的逻辑 System.out.println("Before method: " + method.getName()); // 调用目标方法 Object result = proxy.invokeSuper(obj, args); // 在目标方法执行后的逻辑 System.out.println("After method: " + method.getName()); return result; } } ``` 在上述示例中,我们首先创建了一个`CglibProxyExample`类,实现了`MethodInterceptor`接口。然后,我们通过`Enhancer`类创建了一个代理对象,并设置了目标类和代理逻辑。在`intercept`方法中,我们可以在目标方法执行前后添加自定义的逻辑。 使用CGLIB动态代理时,我们可以通过调用`createProxy`方法来创建代理对象。例如: ```java SomeClass target = new SomeClass(); CglibProxyExample proxyExample = new CglibProxyExample(); SomeClass proxy = (SomeClass) proxyExample.createProxy(target); ``` 这样,我们就可以通过`proxy`对象来调用目标类的方法,并在方法执行前后添加自定义的逻辑。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值