Download After_End/Proxy/src/proxy/ProxyTest.java from zxy0307/JavaWeb: direct link, hf CLI and curl.
- Browser
- Download file 2.38 kB
-
https://huggingface.co/zxy0307/JavaWeb/resolve/main/After_End/Proxy/src/proxy/ProxyTest.java
- Command line
-
hf download hf://zxy0307/JavaWeb/After_End/Proxy/src/proxy/ProxyTest.java
-
curl -L -o ProxyTest.java https://huggingface.co/zxy0307/JavaWeb/resolve/main/After_End/Proxy/src/proxy/ProxyTest.java
2.38 kB
| package proxy; | |
| import java.lang.reflect.InvocationHandler; | |
| import java.lang.reflect.Method; | |
| import java.lang.reflect.Proxy; | |
| import java.util.Arrays; | |
| public class ProxyTest { | |
| public static void main(String[] args) { | |
| //1、创建真实对象 | |
| lenovo lenovo = new lenovo(); | |
| //2、动态代理 增强lenovo对象 | |
| /* | |
| 三个参数: | |
| 1、类加载器 -- 真实对象.getClass().getClassLoader() | |
| 2、接口数组 -- 真实对象..getClass().getInterfaces() | |
| 3、处理器:new InvocationHandler() | |
| */ | |
| SaleComputer proxy_lenovo = (SaleComputer) Proxy.newProxyInstance(lenovo.getClass().getClassLoader(), lenovo.getClass().getInterfaces(), new InvocationHandler() { | |
| /* | |
| 代理逻辑编写的方法:代理对象调用的所有方法,都会触发该方法执行 | |
| 参数: | |
| 1、proxy:代理对象 | |
| 2、method:代理对象调用的方法,所封装的对象 | |
| 3、args:代理对象调用方法时,传递的参数 | |
| */ | |
| public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { | |
| System.out.println("代理方法执行了"); | |
| System.out.println(method.getName()); | |
| System.out.println(Arrays.toString(args)); | |
| //判断是否是sale方法 | |
| if (method.getName().equals("sale")) { | |
| //1、增强参数 | |
| double money = (double) args[0]; | |
| money = money * 0.85; | |
| //使用真实对象调用该方法 | |
| String obj = (String) method.invoke(lenovo, money); | |
| //2、增强方法体 | |
| System.out.println("送货上门..."); | |
| //3、增强返回值 | |
| return obj + "_鼠标垫"; | |
| } else { | |
| //使用真实对象调用该方法 | |
| Object obj = method.invoke(lenovo, args); | |
| return obj; | |
| } | |
| } | |
| }); | |
| //2、调用方法 | |
| String computer = proxy_lenovo.sale(8000); | |
| System.out.println(computer); | |
| proxy_lenovo.show(); | |
| } | |
| } | |