动态代理

来源:互联网 发布:象棋作弊软件 编辑:程序博客网 时间: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
原创粉丝点击