赞
踩
在上一篇博客中写了基于接口的动态代理,其实这两个原理基本差不多,对比学习更好理解。
<dependencies>
<!-- https://mvnrepository.com/artifact/cglib/cglib -->
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>3.2.7</version>
</dependency>
</dependencies>
//生产者
public class Producer{
//销售
public void saleProduce(float money){
System.out.println("销售商品,并拿到钱"+money);
}
//售后
public void afterService(float money){
System.out.println("提供售后服务,并拿到钱"+money);
}
}
public class MyMethodInterceptor implements MethodInterceptor { private Object target; public MyMethodInterceptor(Object target) { this.target = target; } public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable { Object result = null; //获取方法执行的参数 Float money = (Float)args[0]; //判断当前方法是不是销售 if("saleProduce".equals(method.getName())){ result = method.invoke(target, money*0.8f); } return result; } }
public class Client {
public static void main(String[] args) {
//被代理对象
Producer producer = new Producer();
//获取代理对象
Producer proxy =(Producer) Enhancer.create(
producer.getClass(),
new MyMethodInterceptor(producer));
//使用代理对象调用被代理对象中的方法
proxy.saleProduce(10000f);
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。