一个简单的动态代理实现

接口:

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 }

目标:

 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 }

代理:

 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 }

结果:

猜你喜欢

转载自www.cnblogs.com/kill-9/p/9644047.html