基于子类的动态代理:如果是maven工程则需先引入依赖
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.1_3</version>
</dependency>
提供方:第三方cglib库
创建代理类的要求: 被代理类不能是final类
public class Client {
public static void main(String[] args) {
final Producer producer = new Producer();
/**
* create方法的参数
* class:字节码
* 它是用于指定被代理对象字节码的
*
* callback:提供增强的代码
* 它是让我们写如何代理。我们一般都是写一个该接口的实现类,通常情况下都是匿名内部类,但不是必须的
*
* 我们一般写的是该接口的子接口实现类,MethodIntercepter
*
*/
Producer producerCglib =(Producer) Enhancer.create(producer.getClass(),
new MethodInterceptor() {
/**
*
* @param o
* @param method
* @param objects
* 以上三个参数和基于接口的动态代理中invoke方法的参数是一样的
* @param methodProxy:当前执行方法的代理对象
* @return
* @throws Throwable
*/
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
//提供增强的代码
Object returnValue = null;
//获取方法执行的参数
Float money = (Float) objects[0];
//判断当前方法是不是销售
if ("saleProduct".equals(method.getName())) {
returnValue = method.invoke(producer, money * 0.8f);
}
return returnValue;
//return method.invoke(producer,args);
}
});
producerCglib.saleProduct(10000f);
}
}