深入探究Java动态代理

朴灿烈づ我的快乐病毒、 2022-05-20 06:47 282阅读 0赞

深入探究Java动态代理

文章目录

  • 深入探究Java动态代理
      1. Spring实现AOP
      1. JDK动态代理
      1. 动态代理详解
      • Proxy
      • InvocationHandler
      1. 深入探究代理类
      • 4.1 代理类的代码
      • 4.2 invoke方法的第一个参数
        • 题外话

提起Java的动态代理,大家首先就会想到Spring的AOP,Spring在实现AOP的时候,确实有时候是使用Java动态代理机制来实现的,当使用的接口来生成Bean,并且开启了AOP之后,使用的就是动态代理来实现的AOP

1. Spring实现AOP

创建一个项目,并配置SpringAOP:

Bean:

  1. package com.aaa;
  2. /**
  3. * If there are no bugs, it was created by Chen FengYao on 18-7-8;
  4. * Otherwise, Inter don't know who created it either
  5. */
  6. public class Foo implements Inter {
  7. @Override
  8. public void fun(String name) {
  9. System.out.println(name);
  10. }
  11. }

接口:

  1. package com.aaa;
  2. public interface Inter {
  3. void fun(String name);
  4. }

前置通知类:

  1. public class AS {
  2. public void befor(){
  3. System.out.println("before");
  4. }
  5. }

在Spring的配置文件中配置Bean和AOP

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:aop="http://www.springframework.org/schema/aop"
  5. xsi:schemaLocation="http://www.springframework.org/schema/beans
  6. http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
  7. http://www.springframework.org/schema/aop
  8. http://www.springframework.org/schema/aop/spring-aop-4.1.xsd">
  9. <bean class="com.aaa.Foo" id="foo"/>
  10. <bean class="com.aaa.AS" id="as"/>
  11. <aop:config>
  12. <!-- 定义切面 -->
  13. <aop:aspect id="aspect1" ref="as">
  14. <aop:pointcut id="pt" expression="execution(* com.aaa.*.*(..))"/>
  15. <aop:before method="befor" pointcut-ref="pt"/>
  16. </aop:aspect>
  17. </aop:config>
  18. </beans>

最后来一个Main函数来测试运行

  1. package com.aaa;
  2. import org.springframework.context.ApplicationContext;
  3. import org.springframework.context.support.ClassPathXmlApplicationContext;
  4. public class Main {
  5. public static void main(String[] args) {
  6. ApplicationContext context = new ClassPathXmlApplicationContext(
  7. "spring-config.xml");
  8. Inter i = (Inter) context.getBean("foo");
  9. i.fun("input");
  10. }
  11. }

运行结果:
49a8bf48c478cb95c7aeff3c398202b0.png

可以看到我们切点已经正常执行了,那么这个时候我们来看一下生成的Inter对象的类型,修改代码如下:

  1. import org.springframework.context.ApplicationContext;
  2. import org.springframework.context.support.ClassPathXmlApplicationContext;
  3. public class Main {
  4. public static void main(String[] args) {
  5. ApplicationContext context = new ClassPathXmlApplicationContext(
  6. "spring-config.xml");
  7. Inter i = (Inter) context.getBean("foo");
  8. i.fun("input");
  9. System.out.println("-------------------");
  10. System.out.println(i.getClass().getName());
  11. }
  12. }

运行结果:

aa72641337a89200ec5476486dd3cc2a.png

我们看到,实际上Spring为我们生成的对象并不是我们写的Foo类,当我们使用Spring并配置了AOP的时候,Spring就会为我们生成代理类型,这个com.sun.proxy.$Proxy2,就是JDK动态代理所生成的类型

2. JDK动态代理

那么就用JVM动态代理来实现一下切面的功能,保持Foo不变,先看代码:

  1. import java.lang.reflect.InvocationHandler;
  2. import java.lang.reflect.Method;
  3. import java.lang.reflect.Proxy;
  4. /**
  5. * If there are no bugs, it was created by Chen FengYao on 18-7-12;
  6. * Otherwise, I don't know who created it either
  7. */
  8. public class InvocationHandlerImpl implements InvocationHandler {
  9. private Object target;
  10. private InvocationHandlerImpl(Object target) {
  11. this.target = target;
  12. }
  13. public static Object getProxy(Object target){
  14. InvocationHandlerImpl invocationHandler = new InvocationHandlerImpl(target);
  15. return Proxy.newProxyInstance(target.getClass().getClassLoader(),
  16. target.getClass().getInterfaces(),
  17. invocationHandler);
  18. }
  19. @Override
  20. public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
  21. System.out.println("before");
  22. Object result = method.invoke(target, args);
  23. System.out.println("after");
  24. return result;
  25. }
  26. }

然后是Main方法,运行一下,看看效果:

  1. public class Main {
  2. public static void main(String[] args) {
  3. Foo foo = new Foo();
  4. Inter proxy = (Inter) InvocationHandlerImpl.getProxy(foo);
  5. proxy.fun("input");
  6. System.out.println("------------------");
  7. System.out.println(proxy.getClass().getName());
  8. }
  9. }

运行效果:
9e46edc2a34fb75e41838c0ff5670c51.png

发现和刚刚Sping实现的效果是一样的

3. 动态代理详解

要实现JDK动态代理,我们需要两个关键性的类:

  1. import java.lang.reflect.Proxy
  2. import java.lang.reflect.InvocationHandler

我们一个一个的详细来说明:

Proxy

Proxy就是我们生成动态代理使用的类,在需要生成代理对象的时候,我们需要以下几个东西:

  1. classLoader
  2. 接口
  3. invocationHandler对象

classLoader就不需要多说了,大多数 情况下,都可以从目标类获得
第二个参数是你要生成的代理对象所实现的接口类型,这个参数是一个Class类型的数组,如果你不想手动设置进去也可以,只要放入接口类型.class进去就好了,我们生成的代理对象就会去实现这个参数中的接口
第三个参数是一个InvocationHandler对象,也就是我们这个类的对象

InvocationHandler

这个接口可以认为是代理类型与原始类型之间的桥梁因为是动态代理,如何理解这个动态,对应到上面的代码就是InvocationHandlerImpl这个类写好了之后,无论传入什么对象,都能够给他生成对应的代理对象,而这些代理对象又会在调用原始对象的方法(即fun()方法)的时候都能够统一的执行AOP方法,那么为了实现这个目标,就需要有这么一个方法,就是invoke方法,无论调用代理对象的什么方法,都会执行一次invoke方法,这样,我们就可以在这个方法中加入前置通知,和后置通知了,
看这个方法中的代码:

  1. @Override
  2. public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
  3. System.out.println("before");
  4. Object result = method.invoke(target, args);
  5. System.out.println("after");
  6. return result;
  7. }

这里有3个参数,第一个参数proxy是代理对象,我们几乎是用不上它的,甚至可以说完全用不上它。。。
第二个参数是一个Method对象,用过反射的同学应当对这个对象不会感觉陌生,它就是要执行的目标方法,当我们调用代理对象的中的任何方法,都会把这个方法作为method参数传入invoke方法中
而最后一个参数就是这个方法的实参们了
那么这个方法的返回值,就是目标方法的返回值啦
在invoke方法中我们就可以决定我们的逻辑了:
输出的befor就相当于前置通知,在调用目标方法前执行的代码,在这里我们有机会去对参数进行修改
method.invoke就是真正的去执行目标方法,返回值就是result
最后的after就相当与后置通知,在这个里,我们有机会去修改目标方法的返回值
最后将返回值返回给调用方
整个调用过程的流程图如下:
3e205ec77c1771aa01346559ff95bb37.png

4. 深入探究代理类

4.1 代理类的代码

其实写到这我们就已经可以使用JDK的动态代理了,但是有一个小缺陷,我们根本就不知道JDK给我们生成的代理类是什么样子的,所以我们需要想办法知道这个代理类究竟是什么样子的

动态代理类的具体实现在ProxyGenerator.java这个类中,我们要想看到生成的代理类究竟是个什么样子的,就需要使用这个类,使用ProxyGenerator手动生成一个代理类的字节码:

  1. import sun.misc.ProxyGenerator;
  2. import java.io.FileNotFoundException;
  3. import java.io.FileOutputStream;
  4. import java.io.IOException;
  5. /**
  6. * If there are no bugs, it was created by Chen FengYao on 18-7-14;
  7. * Otherwise, I don't know who created it either
  8. */
  9. public class Generator {
  10. public static void generator(Object target){
  11. byte[] b= ProxyGenerator.generateProxyClass(target.getClass().getSimpleName(),target.getClass().getInterfaces());
  12. try (FileOutputStream out = new FileOutputStream("./"+target.getClass().getSimpleName()+".class")){
  13. out.write(b);
  14. } catch (FileNotFoundException e) {
  15. e.printStackTrace();
  16. } catch (IOException e) {
  17. e.printStackTrace();
  18. }
  19. }
  20. }

我们将生成传入对象的代理类,并且将它存在项目的根路径下,文件名就是代理类的名字,运行:

  1. public class Main {
  2. public static void main(String[] args) {
  3. Foo foo = new Foo();
  4. Generator.generator(foo);
  5. }
  6. }

76465ac49536906c0b4a2d1b484f6acd.png

反编译字节码,让我们看看它里面究竟写了什么,当然我用的开发工具是idea,双击打开看到的就是反编译之后的java代码了。。。。

反编译之后的结果:

  1. //
  2. // Source code recreated from a .class file by IntelliJ IDEA
  3. // (powered by Fernflower decompiler)
  4. //
  5. import com.aaa.Inter;
  6. import java.lang.reflect.InvocationHandler;
  7. import java.lang.reflect.Method;
  8. import java.lang.reflect.Proxy;
  9. import java.lang.reflect.UndeclaredThrowableException;
  10. public final class Foo extends Proxy implements Inter {
  11. private static Method m1;
  12. private static Method m3;
  13. private static Method m2;
  14. private static Method m0;
  15. public Foo(InvocationHandler var1) throws {
  16. super(var1);
  17. }
  18. public final boolean equals(Object var1) throws {
  19. try {
  20. return (Boolean)super.h.invoke(this, m1, new Object[]{
  21. var1});
  22. } catch (RuntimeException | Error var3) {
  23. throw var3;
  24. } catch (Throwable var4) {
  25. throw new UndeclaredThrowableException(var4);
  26. }
  27. }
  28. public final void fun(String var1) throws {
  29. try {
  30. super.h.invoke(this, m3, new Object[]{
  31. var1});
  32. } catch (RuntimeException | Error var3) {
  33. throw var3;
  34. } catch (Throwable var4) {
  35. throw new UndeclaredThrowableException(var4);
  36. }
  37. }
  38. public final String toString() throws {
  39. try {
  40. return (String)super.h.invoke(this, m2, (Object[])null);
  41. } catch (RuntimeException | Error var2) {
  42. throw var2;
  43. } catch (Throwable var3) {
  44. throw new UndeclaredThrowableException(var3);
  45. }
  46. }
  47. public final int hashCode() throws {
  48. try {
  49. return (Integer)super.h.invoke(this, m0, (Object[])null);
  50. } catch (RuntimeException | Error var2) {
  51. throw var2;
  52. } catch (Throwable var3) {
  53. throw new UndeclaredThrowableException(var3);
  54. }
  55. }
  56. static {
  57. try {
  58. m1 = Class.forName("java.lang.Object").getMethod("equals", Class.forName("java.lang.Object"));
  59. m3 = Class.forName("com.aaa.Inter").getMethod("fun", Class.forName("java.lang.String"));
  60. m2 = Class.forName("java.lang.Object").getMethod("toString");
  61. m0 = Class.forName("java.lang.Object").getMethod("hashCode");
  62. } catch (NoSuchMethodException var2) {
  63. throw new NoSuchMethodError(var2.getMessage());
  64. } catch (ClassNotFoundException var3) {
  65. throw new NoClassDefFoundError(var3.getMessage());
  66. }
  67. }
  68. }

一点一点的看,首先这个代理继承了Proxy实现了Inter接口,这个接口就是我们在生成代理类时传递进去的接口,然后这个代理类有4个Method类型的全局变量,这4个全局变量就是我们这个类中的各个方法,在最下方的静态代码块中进行赋值的,equals,fun和toString方法是默认会重写的方法,fun方法是我们从接口那继承来的,这些方法的逻辑都是一样的,本质上就一行代码:

  1. super.h.invoke(this, m3, new Object[]{
  2. var1});

就是调用父类中h对象的invoke方法,去到他的父类中,发现这个如下代码:

  1. /**
  2. * the invocation handler for this proxy instance.
  3. * @serial
  4. */
  5. protected InvocationHandler h;

其实就是我们自己写的InvocationHandler,那么也就是说这个代理类啥也不干,就是在从接口那拿来的方法中去调用invocation方法,在这里我们能清晰的看到invoke方法的第一个参数其实就是这个代理类自己

4.2 invoke方法的第一个参数

实际上,我们绝大多数情况下都用不到这个对象,但是如果我们使用链式编程的话,就有可能需要用到这个对象了,例如我们的接口是这样的:

  1. public interface Inter {
  2. void fun(String name);
  3. //链式编程示例
  4. Inter step1();
  5. Inter step2();
  6. }

Foo类实现Inter接口,是这样的:

  1. public class Foo implements Inter {
  2. @Override
  3. public void fun(String name) {
  4. System.out.println(name);
  5. }
  6. @Override
  7. public Inter step1() {
  8. System.out.println("第一步");
  9. return this;
  10. }
  11. @Override
  12. public Inter step2() {
  13. System.out.println("第二步");
  14. return this;
  15. }
  16. }

保持我们的InvocationHandlerImpl不变,来调用一下代理对象看看会发生什么:

  1. public class Main {
  2. public static void main(String[] args) {
  3. Foo foo = new Foo();
  4. Inter inter = (Inter) InvocationHandlerImpl.getProxy(foo);
  5. inter.step1().step2();
  6. }
  7. }

37bcf5568a82a35a3ac370b7a375958e.png

发现结果只有第一个方法能执行我们的before和after,后面的都不生效了,这是因为在invoke方法中我们返回的对象是执行目标类的目标方法的返回值,在执行第一次之后就被替换成了目标对象了,再也不是代理类型了,如果我们想让我们的动态代理正确的被执行,就需要返回代理类型的对象:

  1. @Override
  2. public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
  3. System.out.println("before");
  4. Object result = method.invoke(target, args);
  5. Class<?>[] interfaces = result.getClass().getInterfaces();
  6. System.out.println("after");
  7. if (result == target){
  8. return proxy;
  9. }
  10. return result;
  11. }

重点是返回值前的判断,result==target其实就是判断这个方法是否返回的是this,如果返回的是this,就证明这里需要链式编程,这个方法就需要返回代理类型的对象了,运行结果如下:

d5b18c028e893f69c5647ec414cd457d.png

可以看到两个方法都能正常执行before和after

题外话

在调查invoke方法的第一个参数究竟有什么用的时候,看到了stackoverflow上的一篇帖子:这里面的意思与我上述表示的差不多,但是它的示例代码是这样写的:

接口:

  1. private interface Account {
  2. public Account deposit (double value);
  3. public double getBalance ();
  4. }

handler:

  1. private class ExampleInvocationHandler implements InvocationHandler {
  2. private double balance;
  3. @Override
  4. public Object invoke (Object proxy, Method method, Object[] args) throws Throwable {
  5. // simplified method checks, would need to check the parameter count and types too
  6. if ("deposit".equals(method.getName())) {
  7. Double value = (Double) args[0];
  8. System.out.println("deposit: " + value);
  9. balance += value;
  10. return proxy; // here we use the proxy to return 'this'
  11. }
  12. if ("getBalance".equals(method.getName())) {
  13. return balance;
  14. }
  15. return null;
  16. }
  17. }

注意他在invoke方法中是通过判断接口中的方法名来选择是返回代理对象,还是常规对象,我觉得这是不合理的,因为我们之所以用动态代理而不用静态代理,很大程度上是因为我们要织入的方法是不希望和实际的对象绑定在一起的,就像我们在实际中,很多时候代理都是来开启事物,关闭事物的,就是说无论是实现了什么接口的代理对象,它应当都按照统一的逻辑去执行AOP,但是按照这个写法,我们的Handler就与一个固定的接口绑定在一起了,要是这样的话,我们直接写一个代理类岂不是更方便,直接使用静态代理就行了,没必要再去使用动态代理了

发表评论

表情:
评论列表 (有 0 条评论,282人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Java代理模式探究

    代理模式 我们使用代理对象来代替对真实对象的访问,这样就可以在不修改原目标对象的前提下,提供额外的功能操作,扩展目标对象的功能。 举个例子来说就是相当于我们卖房子,需要

    相关 深入Java动态代理源码

    背景介绍 什么是动态代理? 动态代理,本质上还是代理模式,只不过代理类是在JDK内部产生并创建实例(字节码编辑)。 再者其内部还维护了一个基于弱引用的缓存结构。总结来说:

    相关 深入学习jdk动态代理

    何为代理 代理,即代替主角完成一些额外的事情,例如,经纪人作为明星的代理人和出资洽谈片酬,排期等,而正真参与拍戏的还是明星本人,明星拍完戏后,再有经纪人代理明星去清理片酬等