JDK动态代理机制

实现代码

接口类

 1 package com.lzp.springbootdemo.proxy.dynamicproxy;
 2 
 3 /**
 4  * @Author 14715
 5  * @Date 2022/5/9 11:39
 6  * @Version 1.0
 7  *
 8  * 厂家
 9  */
10 public interface UFactory {
11 
12     // 卖U盘
13     double soldU();
14 
15 }

实现类

 1 package com.lzp.springbootdemo.proxy.dynamicproxy;
 2 
 3 /**
 4  * @Author 14715
 5  * @Date 2022/5/9 12:19
 6  * @Version 1.0
 7  */
 8 public class UFactoryImpl implements UFactory{
 9     
10     @Override
11     public double soldU() {
12         return 25.5;
13     }
14     
15 }

动态代理类

 1 package com.lzp.springbootdemo.proxy.dynamicproxy;
 2 
 3 import java.lang.reflect.InvocationHandler;
 4 import java.lang.reflect.Method;
 5 import java.lang.reflect.Proxy;
 6 
 7 /**
 8  * @Author 14715
 9  * @Date 2022/5/9 12:19
10  * @Version 1.0
11  */
12 public class ProxyFactory implements InvocationHandler {
13 
14     private Object target;
15 
16     public ProxyFactory(Object target) {
17         this.target = target;
18     }
19 
20     @Override
21     public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
22         System.out.println("代理对象调用开始");
23         Object result = method.invoke(target, args);
24         // 增强功能
25         if (result != null) {
26             result = (double) result +  10;
27         }
28         System.out.println("代理对象调用结束");
29         return result;
30     }
31 
32     public <T> T getDynamicInstance(Class<T> ... classes) {
33         return (T) Proxy.newProxyInstance(target.getClass().getClassLoader(), classes, this);
34     }
35 
36 }

测试类

 1 package com.lzp.springbootdemo.proxy.dynamicproxy;
 2 
 3 /**
 4  * @Author 14715
 5  * @Date 2022/5/9 12:22
 6  * @Version 1.0
 7  */
 8 public class ClientTest {
 9     public static void main(String[] args) {
10         ProxyFactory proxyFactory = new ProxyFactory(new UFactoryImpl());
11         UFactory dynamicInstance = proxyFactory.getDynamicInstance(UFactory.class);
12         double v = dynamicInstance.soldU();
13         System.out.println(v);
14     }
15 }

测试效果

 

posted @ 2022-05-09 12:51  没有你哪有我  阅读(26)  评论(0编辑  收藏  举报