基于子类的动态代理:

基于子类的动态代理:

提供者:第三方的CGLib,如果报asmxxxx异常,需要导入asm.jar。

<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.1_3</version>
</dependency>

要求:

  被代理类不能用final修饰的类(最终类)。

涉及的类:

  Enhancer

如何创建代理对象:

  使用Enhancer类中的create方法

create方法的参数:

  Class:字节码

    它是用于指定被代理对象的字节码。

  Callback:用于提供增强的代码

    它是让我们写如何代理。我们一般都是些一个该接口的实现类,通常情况下都是匿名内部类,但不是必须的。

    此接口的实现类都是谁用谁写。

    我们一般写的都是该接口的子接口实现类:MethodInterceptor

 1 Producer cglibProducer = (Producer)Enhancer.create(producer.getClass(), new MethodInterceptor() {
 2             /**
 3              * 执行被代理对象的任何方法都会经过该方法
 4              * @param proxy
 5              * @param method
 6              * @param args
 7              *    以上三个参数和基于接口的动态代理中invoke方法的参数是一样的
 8              * @param methodProxy :当前执行方法的代理对象
 9              * @return
10              * @throws Throwable
11              */
12             public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
13                 //提供增强的代码
14 
15                 //获取方法执行的参数
16                 Object returnValue = method.invoke(producer, args[0]);
17                 }
18                 return returnValue;
19             }
20         });
21         cglibProducer.saleProduct(12000f);
原文地址:https://www.cnblogs.com/mkl7/p/10691939.html