首页 > 编程语言 > 详细

Java动态代理

时间:2020-01-22 23:49:46      阅读:103      评论:0      收藏:0      [点我收藏+]

 

 

接口及实现类

1 public interface DynamicProxy {
2 
3     String sayHello();
4 
5 }
1 public class DynamicProxyImpl implements DynamicProxy {
2 
3     @Override
4     public String sayHello() {
5         return "Hello World!";
6     }
7 
8 }

主要类

 1 public class JdkProxyExample implements InvocationHandler {
 2 
 3     private Object target;
 4 
 5     public Object bind(Object target) {
 6         this.target = target;
 7         return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
 8     }
 9 
10     @Override
11     public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
12         System.out.println("前处理");
13         Object object = method.invoke(this.target, args);
14         System.out.print(object);
15         System.out.println(" 处理中");
16         System.out.println("后处理");
17         return object;
18     }
19 
20 }

 

调用方

1 public class DynamicProxyCaller {
2 
3     public void foo() {
4         JdkProxyExample jdkProxyExample = new JdkProxyExample();
5         DynamicProxy dynamicProxy = (DynamicProxy) jdkProxyExample.bind(new DynamicProxyImpl());
6         System.out.println(dynamicProxy.sayHello());
7     }
8 
9 }

Java动态代理

原文:https://www.cnblogs.com/bxcube/p/12229964.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!