1.看图
2.实现类Producer:
package com.itheima.cglib;
import com.itheima.proxy.IProducer;
/*
* 生产厂家
* */
public class Producer{
/*
* 销售
* */
public void saleProduct(float money) {
System.out.println("销售产品并且拿到钱:"+money);
}
/*
* 售后
* */
public void afterService(float money) {
System.out.println("提供售后并且拿到钱:"+money);
}
}
3.模拟用户Client:
package com.itheima.cglib;
import com.itheima.proxy.IProducer;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/*
* 模拟一个消费者
* */
public class Client {
public static void main(String[] args) {
final Producer producer = new Producer();
/*
* 动态代理:
* 特点:字节码随用随创建,随用随加载
* 作用:不修改源码的基础上对方法进行增强(实现类方法)
* 分类:
* 基于子类的动态代理
* 基于子类的动态代理:
* 涉及的类:Enhancer
* 提供者:第三方cglib库
* 如何创建代理对象:
* 使用Enhancer类中的create方法
* 创建代理对象的要求:
* 被代理类不能是最终类(最终类就不能创建子类了)
* create方法的参数:
* Class:字节码
* 作用:他是用于加载代理对象字节码的。写的是被代理对象的类加载器。(代理谁就写谁的类加就行:)。固定写法
* Proxy.newProxyInstance().getClass().getClassLoader()
*
* Callback: 用于提供增强的代码
* 作用:他是让我们写如何代理。我们一般都是写一个该接口的实现类。通常情况下都是匿名内部类,但不是必须的
* 此接口的实现类都是谁用谁写。
* 我们一般写的都是该接口的子接口实现类:MethodInterceptor
*
* */
/*代理创建*/
Producer cglibProducer =(Producer) Enhancer.create(producer.getClass(), new MethodInterceptor() {
/*
* 执行该被代理对象的任何方法都会经过该方法
* 方法参数的含义
* proxy 代理对象的引用
* method 当前执行的方法
* args 当前执行的方法所需的参数
* 以上三个参数和接口的动态代理中invoke方法的参数是一样的
* MethodProxy 当前执行的代理对象
* return 返回值都是一样的
* 总的来说:就是拦截我的方法并且增强(改变)
* */
@Override
public Object intercept(Object proxy , Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
Object returnValue = null;
//1.获取参数
Float money = (Float)args[0];
//2.获取并且拦截
if ("saleProduct".equals(method.getName())){
returnValue = method.invoke(producer,money*0.75f);
}
return returnValue;
}
});
/*经销商去销售*/
cglibProducer.saleProduct(10000.0f);
/*也即是说:proxyProducer执行了这个方法,然后就被拦截,进行增强(改变)*/
/*优势就是:没有改变实现类而去增强(改变)的了该方法*/
/*2.基于子类的代理*/
}
}