动态代理
来源:互联网 发布:象棋作弊软件 编辑:程序博客网 时间:2024/06/04 01:32
首先我们需要有一个接口Calculator和接口的一个实现类MyCalculator
然后我们定义自己的invocationhandler,代码如下:
import java.lang.reflect.InvocationHandler;import java.lang.reflect.Method;import java.lang.reflect.Proxy;public class CalculatorProxy implements InvocationHandler { private Calculator target ;//这是需要做代理的目标对象 //这是一个私有的构造方法,不对外公开 private CalculatorProxy(Calculator target) { this.target = target; } //这是一个对外公开的静态方法,传入一个目标对象,返回其代理对象 public static Calculator getInstance(Calculator target){ //创建一个invocationhandler实例 InvocationHandler calproxy = new CalculatorProxy(target); //使用proxy类的newProxyInstance方法产生代理对象 return (Calculator)Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), calproxy); } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { //执行方法前执行的代码 //System.out.println(method.getName()+"is begin runing"); //执行 Object result = method.invoke(this.target, args); //执行方法后执行的代码 //System.out.println(method.getName()+"is end runing"); return result; }}
现在我们可以使用代理了:
Calculator cal = new MyCalculator(); Calculator proxy = CalculatorProxy.getInstance(cal);
0 0
- 代理-->静态代理&动态代理
- 动态代理
- 动态代理
- 动态代理
- 动态代理
- 动态代理
- 动态代理
- 动态代理
- 动态代理
- 动态代理
- 动态代理
- 动态代理
- 动态代理
- 动态代理
- 动态代理
- 动态代理
- 动态代理
- 动态代理
- 【转自EMC中文支持论坛】探秘I/O队列对磁盘性能的影响
- mac 安装wget
- leetcode第53题-Maximum Subarray
- 关于genymotion模拟器无法启动的问题
- vb.net使用Newtonsoft.JSON解析JSON字串心得
- 动态代理
- 进程的通信方式及特点
- epoll详解
- LeetCode——Factorial Trailing Zeroes
- 基于SDN的SVC视频组播系统搭建二
- 擅长排列的小明
- HttpClient初步使用方法
- ACM大量习题题库及建议培养计划
- 第九章作业