java动态代理Dynamic Proxy

1.被代理对象的接口:

1
2
3
4
5
6
package test.dynamicproxy;
 
public interface TargetInterface {
    public void SayHello();
    public int sum(int a ,int b);
}

 

2.被代理的对象:

1
2
3
4
5
6
7
8
9
10
11
package test.dynamicproxy;
 
public class Target implements TargetInterface {
 
    public void SayHello(){
        System.out.println("Hello");
    }
    public int sum(int a, int b) {
        return a+b;
    }
}

 

3.InvocationHandler包装:

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
package test.dynamicproxy;
 
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
 
public class TargetInvocationHandler implements InvocationHandler {
 
    private Object object;
    public TargetInvocationHandler(Object obj){
        this.object=obj;
    }
     
    public Object invoke(Object proxy, Method method, Object[] args2)
    throws Throwable
    {
        doBefore();
        Object result = method.invoke(object, args2);
        doAfter();
        return result;
    }
 
    public void doBefore(){
        System.out.println("do before");
    }
 
    public void doAfter(){
        System.out.println("do after");
    }
}

4.测试类:

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
package test.dynamicproxy;
 
import java.lang.reflect.Proxy;
 
public class TestDynamicProxy {
 
    /**
     * @param args
     */
    public static void main(String[] args) {
        Target t=new Target();
        TargetInvocationHandler handler=new TargetInvocationHandler(t);
         
        TargetInterface proxy = (TargetInterface) Proxy.newProxyInstance(
                t.getClass().getClassLoader(),
                t.getClass().getInterfaces(),
                handler);
                 
        proxy.SayHello();
 
        int b=proxy.sum(10, 20);
        System.out.println(b);
    }
 
}

posted @   庚武  Views(253)  Comments(0Edit  收藏  举报
点击右上角即可分享
微信分享提示