老生常谈java动态代理

java 里面动态代理非常重要  spring   mybatis  里面大量使用此技术,技术使用并不复杂,巩固下:

1.JDK 动态代理

 

 1 //创建一个接口
 2     interface IPerson{
 3         @Ignore
 4         void say();
 5     }
 6 
 7 
 8 //实现 接收回调的handler
 9     static class LogHandler implements InvocationHandler{
10         private Object obj;
11         public LogHandler(Object target){
12             obj=target;
13         }
14         @Override
15         public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
16             System.out.println("invoke...."+method.getName());
17             Ignore ignore= method.getAnnotation(Ignore.class);
18             //至于实际调用了什么方法并不重要 代理到这里就完成了 这里换成其他调用一样没问题  不过标准方式是这样使用
19             return method.invoke(obj,args);
20         }
21     }
22 
23 
24 @Test
25     void test1() {
26         Person person=new Person();
27         //创建接口的代理对象
28         IPerson per=(IPerson)
29                 Proxy.newProxyInstance(Person.class.getClassLoader(),
30                         Person.class.getInterfaces(),new LogHandler(person));
31 
32         per.say();
33     }
34 
35 
36 static class Person implements IPerson{
37         @Override
38         public void say() {
39             System.out.println("say....");
40         }
41     }

2. CGLIB 动态代理

 1 //创建一个拦截对象
 2     static class  MyCGLibMethodInterceptor implements MethodInterceptor{
 3         @Override
 4         public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
 5             System.out.println("say....intercept___"+method.getName());
 6             Object oo=methodProxy.invokeSuper(o,objects);
 7             return oo;
 8         }
 9     }
10 
11 @Test
12     void  testCGLib(){
13         //创建代理对象 直接用类搞,无需接口
14         Enhancer enhancer=new Enhancer();
15         enhancer.setSuperclass(Person.class);
16         enhancer.setCallback(new MyCGLibMethodInterceptor());
17         Person person=(Person) enhancer.create();
18         person.say();
19     }
20 
21 static class Person implements IPerson{
22         @Override
23         public void say() {
24             System.out.println("say....");
25         }
26     }

 

posted @ 2023-06-28 15:27  dint  阅读(4)  评论(0编辑  收藏  举报