实现一个JDK代理demo

时间:2022-02-03 15:15:01

JDK代理,非常简单地实现了动态代理(首先是实现对应的InvocationHandler;然后,以接口来为被调用目标构建代理对象,代理对象简介运行调用目标,并提供额外逻辑插入)

缺点:它是只能以接口为中心的。优点:依赖JDK,更稳定可靠,跟着JDK升级,代码简单。

 

 1 package jesse.test;
 2 
 3 import java.lang.reflect.InvocationHandler;
 4 import java.lang.reflect.Method;
 5 import java.lang.reflect.Proxy;
 6 
 7 interface Hello{
 8     void sayHello();
 9 }
10 
11 class HelloImpl implements Hello{
12 
13     @Override
14     public void sayHello() {
15         System.out.println("my hello");
16     }
17     
18 }
19 
20 class MyInvocationHandler implements InvocationHandler{
21     private Object target;
22     public MyInvocationHandler(Object target) {
23         super();
24         this.target = target;
25     }
26     @Override
27     public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
28         System.out.println("proxy invoke sayhello");
29         Object result = method.invoke(target, args);
30         return result;
31     }
32 }
33 
34 public class MyJDKProxy {
35     public static void main(String[] args) {
36         HelloImpl hello = new HelloImpl();
37         MyInvocationHandler handler = new MyInvocationHandler(hello);
38         //构造代码实例
39         Hello proxyHello = (Hello)Proxy.newProxyInstance(HelloImpl.class.getClassLoader(), HelloImpl.class.getInterfaces(),handler);
40         //调用代理方法
41         proxyHello.sayHello();
42     }
43     
44 }