动态代理

mac2022-06-30  23

1.现实生活代理

卖票接口:抽象对象,规定要有卖票的方法 你买火车票 -> 黄牛 -> 12306 你买电脑 -> 电脑的代理商 -> 电脑厂家

2.代理模式三要素

1.真实对象: 12306 2.代理对象: 黄牛 3.抽象对象: 卖票的接口

3.什么是动态代理

在程序运行的过程中创建代理对象

4.代理模式好处

1.对方法进行增强 2.可以拦截方法

5.动态代理的API

Proxy类:

static Object newProxyInstance​(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h)创建代理对象返回值Object: 创建出代理对象ClassLoader loader: 类加载器Class<?>[] interfaces: 接口数组, 新建的代理对象会实现指定的接口InvocationHandler h: 执行处理器, 当代理对象调用方法时,就会执行InvocationHandler的invoke方法 public static void main(String[] args) { // 创建真实对象 ArrayList<String> list = new ArrayList<>(); // static Object newProxyInstance​(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h) // 创建代理对象 // 返回值Object: 创建出代理对象 // ClassLoader loader: 类加载器, 自定义的类名.class.getClassLoader() // Class<?>[] interfaces: 接口数组, 新建的代理对象会实现指定的接口 // InvocationHandler h: 执行处理器, 当代理对象调用方法时,就会执行InvocationHandler的invoke方法 List daiLi = (List) Proxy.newProxyInstance( Demo16.class.getClassLoader(), new Class[]{List.class}, // ArrayList.class.getInterfaces() 得到类的所有实现的接口 new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // Object proxy: 代理对象,我们一般不处理 // Method method: 被调用的方法 // Object[] args: 调用方法时的参数 // System.out.println("method = " + method); // System.out.println("args: " + Arrays.toString(args)); // 拦截remove if (method.getName().equals("remove")) { System.out.println("我拦截remove,老子什么都不干"); return false; } else { // 增强 long start = System.currentTimeMillis(); // 调用真实的对象的方法 Object result = method.invoke(list, args); long end = System.currentTimeMillis(); // 统计时间 System.out.println(method.getName() + "消耗时间: " + (end - start)); return result; } } } ); daiLi.add("貂蝉"); daiLi.add("西施"); daiLi.add("杨玉环"); daiLi.set(1, "呵呵"); daiLi.remove(1); System.out.println(daiLi.size()); System.out.println(list); }
最新回复(0)