一個簡單的動態代理實現

接口:java

1 package spring.aop; 2 
3 public interface Arithmetic { 4 
5  Integer add(Integer a,Integer b); 6  Integer sub(Integer a,Integer b); 7    
8 }

目標:spring

 1 package spring.aop;  2 
 3 public class ArithmeticImpl implements Arithmetic{  4 
 5  @Override  6     public Integer add(Integer a, Integer b) {  7         System.out.println("add -> "+(a+b));  8         return a+b;  9  } 10 
11  @Override 12     public Integer sub(Integer a, Integer b) { 13         System.out.println("sub -> "+(a-b)); 14         return a-b; 15  } 16     
17 
18 }

代理:ide

 1 package spring.aop;  2 
 3 import java.lang.reflect.InvocationHandler;  4 import java.lang.reflect.Proxy;  5 import java.util.Arrays;  6 
 7 /**
 8  * 動態代理  9  */
10 public class ArithmeticProxy { 11 
12     private Arithmetic target; 13 
14     public Arithmetic getPoxy(){ 15         Arithmetic proxy = null; 16 
17         //定義代理類的類加載器
18         ClassLoader loader = target.getClass().getClassLoader(); 19 
20         //代理類要實現的接口列表,也就是具備那些方法,是代理對象的類型
21         Class[] interfaces = new Class[]{Arithmetic.class}; 22 
23         //調用代理對象的方法時,執行的代碼
24         /**
25  * proxy1 當前代理對象 26  * method 正在調用的方法 27  * args 調用方法傳遞的參數 28          */
29         InvocationHandler h = (proxy1, method, args) -> { 30             String name = method.getName(); 31             //前置
32             System.out.println("method:"+name+"start:"+ Arrays.asList(args)); 33 
34             //執行方法
35             Object result = method.invoke(target,args); 36 
37             //後置
38             System.out.println("method:"+name+"end:"+ Arrays.asList(args)); 39             return result; 40  }; 41         proxy = (Arithmetic) Proxy.newProxyInstance(loader,interfaces,h); 42 
43         return proxy; 44  } 45 
46     public ArithmeticProxy(Arithmetic target) { 47         this.target = target; 48  } 49 }

測試類:測試

 1 package spring.aop;  2 
 3 public class AOP {  4 
 5     public static void main(String[] args){  6         ArithmeticImpl target = new ArithmeticImpl();  7         Arithmetic proxy = new ArithmeticProxy(target).getPoxy();  8 
 9         proxy.add(3,5); 10         proxy.sub(3,5); 11 
12  } 13 }

結果:this

相關文章
相關標籤/搜索