JDK动态代理

 1 package Two_Test1;
 2 
 3 //接口
 4 public interface HelloWorld {
 5     public void sayHelloWorld();
 6     
 7     public void eat();
 8     
 9     public void run();
10     
11     public void sleep();
12 
13 }
 1 package Two_Test1;
 2 
 3 
 4 //接口的实现类
 5 public class HelloWorldImpl implements HelloWorld {
 6 
 7     @Override
 8     public void sayHelloWorld() {
 9         System.out.println("hello world!!!");
10         
11     }
12 
13     @Override
14     public void eat() {
15         
16         System.out.println("eat----吃饭");
17     }
18 
19     @Override
20     public void run() {
21         // TODO Auto-generated method stub
22         System.out.println("run-----跑步");
23     }
24 
25     @Override
26     public void sleep() {
27         // TODO Auto-generated method stub
28         System.out.println("sleep-------睡觉");
29     }
30 
31 }
 1 package Two_Test1;
 2 
 3 import java.lang.reflect.InvocationHandler;
 4 import java.lang.reflect.Method;
 5 import java.lang.reflect.Proxy;
 6 
 7 
 8 /*
 9  * 代理的两个步骤
10  * 1. 代理对象和真实对象建立代理关系
11  * 2. 实现代理对象的代理逻辑方法
12  */
13 public class JdkProxyExample implements InvocationHandler {
14 
15     //真实对象
16     private Object target = null;
17 
18     /*
19      * 建立代理对象和真实对象的代理关系,并返回代理对象
20      * @param target 真实对象
21      * @return 代理对象
22      */
23     public Object bind(Object target) {
24         this.target = target;
25         return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
26     }
27     
28     
29     
30     /*
31      * 代理方法逻辑
32      * @param proxy 代理对象
33      * @param method 当前调度方法
34      * @param args 当前方法参数
35      * @return 代理结果返回
36      * @throws Throwable 异常
37      */
38 
39     @Override
40     public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
41         System.out.println("进入代理逻辑方法");
42         System.out.println("在调度真是对象之前的服务");
43         Object obj = method.invoke(target, args);
44         System.out.println("在调度真实对象之后的服务");
45         return obj;
46     }
47 
48 }
 1 package Two_Test1;
 2 
 3 public class Test {
 4 
 5     public static void main(String[] args) {
 6 
 7         Test t = new Test();
 8 
 9         t.testJgkProxy();
10 
11     }
12 
13     public void testJgkProxy() {
14 
15         JdkProxyExample jdk = new JdkProxyExample();
16 
17         HelloWorld proxy = (HelloWorld) jdk.bind(new HelloWorldImpl());
18 
19         proxy.sayHelloWorld();
20         proxy.eat();
21         proxy.run();
22         proxy.sleep();
23 
24     }
25 
26 }

运行结果:

注:结果不是下面的情况

进入代理逻辑方法
在调度真是对象之前的服务

hello world!!!

eat----吃饭

run-----跑步

sleep-------睡觉

在调度真实对象之后的服务

 

posted @ 2021-04-18 23:09  L1998  阅读(59)  评论(0)    收藏  举报