首页 > 其他 > 详细

about proxy

时间:2014-02-18 15:12:27      阅读:342      评论:0      收藏:0      [点我收藏+]

一、实现InvacatinHandler

Exmaple:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
 
 
public class MyInvocationhandler implements InvocationHandler{
 
    private Object target;
     
    @Override
    public Object invoke(Object proxy, Method method, Object[] args)
            throws Throwable {
        // TODO 调用一个类方法在其开始和结束时分别先执行method1和method2
        Dogutil du=new Dogutil(); 
        //要开始时插入的method1方法
        du.method1();
        //Object result=invoke(target, method, args);
        Object result=method.invoke(target,args); 
        //要结束时插入的method1方法
        du.method2();
        return result;
    }
 
    public Object getTarget() {
        return target;
    }
 
    public void setTarget(Object target) {
        this.target = target;
    }
 
}

  二、实现proxyfactory

Example:

bubuko.com,布布扣
import java.lang.reflect.Proxy;


public class proxyfactory {
public static Object getproxy(Object traget){
    MyInvocationhandler handler=new MyInvocationhandler();
    handler.setTarget(traget);

    return Proxy.newProxyInstance(traget.getClass().getClassLoader(),
            traget.getClass().getInterfaces(), handler);
}
}
bubuko.com,布布扣

  三、编写测试类。

Example:

bubuko.com,布布扣
public class test {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO 使用代理调用gundog类方法
            Dog traget=new gundog();
            Dog dog =(Dog)proxyfactory.getproxy(traget);
            dog.info();
            dog.run();
    }

}
bubuko.com,布布扣

about proxy

原文:http://www.cnblogs.com/weiwoduhigh/p/3553656.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!