首页 > 代码库 > java代理Proxy

java代理Proxy

首先是静态代理:

 1 public class Test1 {
 2 
 3     public static void main(String[] args) {
 4         IA a = new APoxy(new A());
 5         a.doJob();
 6     }
 7 
 8 }
 9 //功能接口
10 interface IA{
11     public void doJob();
12 }
13 //委托类
14 class A implements IA{
15 
16     @Override
17     public void doJob() {
18         System.out.println("doJob");
19     }
20     
21 }
22 //代理类
23 class APoxy implements IA{
24     private IA a = null;
25     public APoxy(IA a){
26         this.a = a;
27     }
28     @Override
29     public void doJob(){
30         beforeDoJob();
31         a.doJob();
32         afterDoJob();
33     }
34 
35     private void afterDoJob() {
36         System.out.println("afterDoJob");
37     }
38 
39     private void beforeDoJob() {
40         System.out.println("beforeDoJob");
41     }
42 }

动态代理:

 1 import java.lang.reflect.InvocationHandler;
 2 import java.lang.reflect.Method;
 3 import java.lang.reflect.Proxy;
 4 
 5 public class Test2 {
 6     public static void main(String... strings) {
 7         AAProxy ap = new AAProxy();
 8         IAA aa = (IAA) ap.bind(new AA());
 9         aa.doJob();
10         
11         
12     }
13 }
14 
15 interface IAA {
16     public void doJob();
17 }
18 
19 class AA implements IAA {
20     //委托类
21     @Override
22     public void doJob() {
23         System.out.println("doJob");
24     }
25 
26 }
27 //代理类                                                               实现InvocationHandler
28 class AAProxy implements InvocationHandler {
29     private Object obj;
30     //绑定对象
31     public Object bind(IAA iaa) {
32         obj = iaa;
33         return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj
34                 .getClass().getInterfaces(), this);
35     }
36     //处理调用方法
37     @Override
38     public Object invoke(Object proxy, Method method, Object[] args)
39             throws Throwable {
40         System.out.println("before");
41         Object result = method.invoke(obj, args);
42         System.out.println("after");
43         return result;
44     }
45 
46 
47 }

Cglib代理。。。第三方代理。。。稍后补充