动态代理是使用非常广泛的技术,诸如大名鼎鼎的spring、mybatis等框架都大量使用动态代理。动态代理区别于静态代理的地方在于:静态代理需要为每一个被代理类都创建一个代理类,在编译期代理类就已经生成,而动态代理则是在程序运行期动态地生成代理类,所有被代理对象的执行逻辑都被转移到InvocationHandler对象的invoke方法,在invoke方法里通过反射来调用被代理的对象方法,当然也可以执行其它的逻辑。动态代理的一个显而易见的好处是:不用为每个被代理类都手动创建一个代理类。
    按照惯例,先谈使用再讲原理。举个例子先。
    场景:七夕临近,公司交友社团本着消灭单身狗的美好愿景,为闷骚的程序猿(媛)们开通了月老服务,任何有心仪目标但是又羞于开口的单身程序狗都可以委托“月老”来约心中的男神女神出来。
    Suitor(追求者)接口

    1. public interface Suitor {
    2. void sayHi(Beauty beauty);
    3. }

    image.gif
    Programmer(程序猿)

    1. public class Programmer implements Suitor {
    2. @Override
    3. public void sayHi(Beauty beauty) {
    4. System.out.println("Hello, " + beauty.getName() + "! Would you like to have dinner with me tonight?");
    5. }
    6. }

    Beauty(MM)

    1. public class Beauty {
    2. private String name;
    3. public Beauty(String name) {
    4. this.name = name;
    5. }
    6. public String getName() {
    7. return name;
    8. }
    9. }

    image.gif
    处理邀请MM动作的InvocationHandler

    1. public class SuitorInvocationHandler implements InvocationHandler {
    2. Suitor suitor;
    3. public SuitorInvocationHandler(Suitor suitor) {
    4. this.suitor = suitor;
    5. }
    6. @Override
    7. public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    8. return method.invoke(suitor, args);
    9. }
    10. }

    image.gif
    测试,创建代理对象并对MM发出邀请

    1. public class DynamicProxyTest {
    2. @Test
    3. public void test() {
    4. Beauty beauty = new Beauty("MM");
    5. InvocationHandler handler = new SuitorInvocationHandler(new Programmer());
    6. Suitor suitor = (Suitor) Proxy.newProxyInstance(Suitor.class.getClassLoader(), new Class<?>[]{Suitor.class}, handler);
    7. suitor.sayHi(beauty);
    8. }
    9. }

    image.gif
    结果

    1. Hello, MM! Would you like to have dinner with me tonight?

    可见,代理对象成功地激发了被代理对象想执行的业务逻辑。
    那么,代理对象到底是如何生成的,业务逻辑又是如何转嫁到InvocationHandler上的呢?
    Proxy.newProxyInstance中调用生成代理类的逻辑 Class<?> cl = getProxyClass0(loader, intfs);

    1. @CallerSensitive
    2. public static Object newProxyInstance(ClassLoader loader,
    3. Class<?>[] interfaces,
    4. InvocationHandler h)
    5. throws IllegalArgumentException
    6. {
    7. Objects.requireNonNull(h);
    8. final Class<?>[] intfs = interfaces.clone();
    9. final SecurityManager sm = System.getSecurityManager();
    10. if (sm != null) {
    11. checkProxyAccess(Reflection.getCallerClass(), loader, intfs);
    12. }
    13. /*
    14. * Look up or generate the designated proxy class.
    15. * 生成代理类
    16. */
    17. Class<?> cl = getProxyClass0(loader, intfs);
    18. /*
    19. * Invoke its constructor with the designated invocation handler.
    20. */
    21. try {
    22. if (sm != null) {
    23. checkNewProxyPermission(Reflection.getCallerClass(), cl);
    24. }
    25. final Constructor<?> cons = cl.getConstructor(constructorParams);
    26. final InvocationHandler ih = h;
    27. if (!Modifier.isPublic(cl.getModifiers())) {
    28. AccessController.doPrivileged(new PrivilegedAction<Void>() {
    29. public Void run() {
    30. cons.setAccessible(true);
    31. return null;
    32. }
    33. });
    34. }
    35. return cons.newInstance(new Object[]{h});
    36. } catch (IllegalAccessException|InstantiationException e) {
    37. throw new InternalError(e.toString(), e);
    38. } catch (InvocationTargetException e) {
    39. Throwable t = e.getCause();
    40. if (t instanceof RuntimeException) {
    41. throw (RuntimeException) t;
    42. } else {
    43. throw new InternalError(t.toString(), t);
    44. }
    45. } catch (NoSuchMethodException e) {
    46. throw new InternalError(e.toString(), e);
    47. }
    48. }

    image.gif
    最终生成代理类的逻辑在Proxy.ProxyClassFactory.apply方法内

    1. public Class<?> apply(ClassLoader loader, Class<?>[] interfaces) {
    2. Map<Class<?>, Boolean> interfaceSet = new IdentityHashMap<>(interfaces.length);
    3. for (Class<?> intf : interfaces) {
    4. /*
    5. * Verify that the class loader resolves the name of this
    6. * interface to the same Class object.
    7. */
    8. Class<?> interfaceClass = null;
    9. try {
    10. interfaceClass = Class.forName(intf.getName(), false, loader);
    11. } catch (ClassNotFoundException e) {
    12. }
    13. if (interfaceClass != intf) {
    14. throw new IllegalArgumentException(
    15. intf + " is not visible from class loader");
    16. }
    17. /*
    18. * Verify that the Class object actually represents an
    19. * interface.
    20. */
    21. if (!interfaceClass.isInterface()) {
    22. throw new IllegalArgumentException(
    23. interfaceClass.getName() + " is not an interface");
    24. }
    25. /*
    26. * Verify that this interface is not a duplicate.
    27. */
    28. if (interfaceSet.put(interfaceClass, Boolean.TRUE) != null) {
    29. throw new IllegalArgumentException(
    30. "repeated interface: " + interfaceClass.getName());
    31. }
    32. }
    33. String proxyPkg = null; // package to define proxy class in
    34. int accessFlags = Modifier.PUBLIC | Modifier.FINAL;
    35. /*
    36. * Record the package of a non-public proxy interface so that the
    37. * proxy class will be defined in the same package. Verify that
    38. * all non-public proxy interfaces are in the same package.
    39. */
    40. for (Class<?> intf : interfaces) {
    41. int flags = intf.getModifiers();
    42. if (!Modifier.isPublic(flags)) {
    43. accessFlags = Modifier.FINAL;
    44. String name = intf.getName();
    45. int n = name.lastIndexOf('.');
    46. String pkg = ((n == -1) ? "" : name.substring(0, n + 1));
    47. if (proxyPkg == null) {
    48. proxyPkg = pkg;
    49. } else if (!pkg.equals(proxyPkg)) {
    50. throw new IllegalArgumentException(
    51. "non-public interfaces from different packages");
    52. }
    53. }
    54. }
    55. if (proxyPkg == null) {
    56. // if no non-public proxy interfaces, use com.sun.proxy package
    57. proxyPkg = ReflectUtil.PROXY_PACKAGE + ".";
    58. }
    59. /*
    60. * Choose a name for the proxy class to generate.
    61. */
    62. long num = nextUniqueNumber.getAndIncrement();
    63. String proxyName = proxyPkg + proxyClassNamePrefix + num;
    64. /*
    65. * Generate the specified proxy class.
    66. */
    67. byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
    68. proxyName, interfaces, accessFlags);
    69. try {
    70. return defineClass0(loader, proxyName,
    71. proxyClassFile, 0, proxyClassFile.length);
    72. } catch (ClassFormatError e) {
    73. /*
    74. * A ClassFormatError here means that (barring bugs in the
    75. * proxy class generation code) there was some other
    76. * invalid aspect of the arguments supplied to the proxy
    77. * class creation (such as virtual machine limitations
    78. * exceeded).
    79. */
    80. throw new IllegalArgumentException(e.toString());
    81. }
    82. }

    image.gif
    真正生成类字节码文件的逻辑在byte[] proxyClassFile = ProxyGenerator.generateProxyClass(proxyName, interfaces, accessFlags)。上面主要做的是接口校验、生成类名和确定代理类的访问修饰符等工作。那我们接着看看代理类具体是如何生成的吧。

    1. private byte[] generateClassFile() {
    2. // 将Object类中的方法添加到代理类中
    3. this.addProxyMethod(hashCodeMethod, Object.class);
    4. this.addProxyMethod(equalsMethod, Object.class);
    5. this.addProxyMethod(toStringMethod, Object.class);
    6. Class[] var1 = this.interfaces;
    7. int var2 = var1.length;
    8. int var3;
    9. Class var4;
    10. // 获取接口中的所有方法并添加到代理类中
    11. for(var3 = 0; var3 < var2; ++var3) {
    12. var4 = var1[var3];
    13. Method[] var5 = var4.getMethods();
    14. int var6 = var5.length;
    15. for(int var7 = 0; var7 < var6; ++var7) {
    16. Method var8 = var5[var7];
    17. this.addProxyMethod(var8, var4);
    18. }
    19. }
    20. Iterator var11 = this.proxyMethods.values().iterator();
    21. List var12;
    22. // 验证具有相同方法签名的方法返回类型是否相同
    23. while(var11.hasNext()) {
    24. var12 = (List)var11.next();
    25. checkReturnTypes(var12);
    26. }
    27. Iterator var15;
    28. try {
    29. // 添加代理类的构造方法
    30. this.methods.add(this.generateConstructor());
    31. var11 = this.proxyMethods.values().iterator();
    32. while(var11.hasNext()) {
    33. var12 = (List)var11.next();
    34. var15 = var12.iterator();
    35. while(var15.hasNext()) {
    36. ProxyGenerator.ProxyMethod var16 = (ProxyGenerator.ProxyMethod)var15.next();
    37. // 代理类的字段都是Method类型,存储的待invoke的接口方法和从Object继承的方法
    38. // 字段用private static修饰,10是ACC_PRIVATE和ACC_STATIC相与的结果
    39. this.fields.add(new ProxyGenerator.FieldInfo(var16.methodFieldName, "Ljava/lang/reflect/Method;", 10));
    40. // 生成代理类方法
    41. this.methods.add(var16.generateMethod());
    42. }
    43. }
    44. // 生成静态代码块初始化私有静态字段
    45. this.methods.add(this.generateStaticInitializer());
    46. } catch (IOException var10) {
    47. throw new InternalError("unexpected I/O Exception", var10);
    48. }
    49. // 如果方法数量超过65535个则抛异常
    50. if (this.methods.size() > 65535) {
    51. throw new IllegalArgumentException("method limit exceeded");
    52. } else if (this.fields.size() > 65535) {
    53. throw new IllegalArgumentException("field limit exceeded");
    54. } else {
    55. this.cp.getClass(dotToSlash(this.className));
    56. this.cp.getClass("java/lang/reflect/Proxy");
    57. var1 = this.interfaces;
    58. var2 = var1.length;
    59. for(var3 = 0; var3 < var2; ++var3) {
    60. var4 = var1[var3];
    61. this.cp.getClass(dotToSlash(var4.getName()));
    62. }
    63. this.cp.setReadOnly();
    64. ByteArrayOutputStream var13 = new ByteArrayOutputStream();
    65. DataOutputStream var14 = new DataOutputStream(var13);
    66. try {
    67. var14.writeInt(-889275714);
    68. var14.writeShort(0);
    69. var14.writeShort(49);
    70. this.cp.write(var14);
    71. var14.writeShort(this.accessFlags);
    72. var14.writeShort(this.cp.getClass(dotToSlash(this.className)));
    73. var14.writeShort(this.cp.getClass("java/lang/reflect/Proxy"));
    74. var14.writeShort(this.interfaces.length);
    75. Class[] var17 = this.interfaces;
    76. int var18 = var17.length;
    77. for(int var19 = 0; var19 < var18; ++var19) {
    78. Class var22 = var17[var19];
    79. var14.writeShort(this.cp.getClass(dotToSlash(var22.getName())));
    80. }
    81. var14.writeShort(this.fields.size());
    82. var15 = this.fields.iterator();
    83. while(var15.hasNext()) {
    84. ProxyGenerator.FieldInfo var20 = (ProxyGenerator.FieldInfo)var15.next();
    85. var20.write(var14);
    86. }
    87. var14.writeShort(this.methods.size());
    88. var15 = this.methods.iterator();
    89. while(var15.hasNext()) {
    90. ProxyGenerator.MethodInfo var21 = (ProxyGenerator.MethodInfo)var15.next();
    91. var21.write(var14);
    92. }
    93. var14.writeShort(0);
    94. return var13.toByteArray();
    95. } catch (IOException var9) {
    96. throw new InternalError("unexpected I/O Exception", var9);
    97. }
    98. }
    99. }

    image.gif
    那么生成的代理类到底长什么样子呢?通过以下代码,将内存中的代理类字节数组写入文件。

    1. byte[] classFile = ProxyGenerator.generateProxyClass("$Proxy0", Programmer.class.getInterfaces());
    2. FileOutputStream fos = new FileOutputStream(new File("programmer.class"));
    3. try {
    4. fos.write(classFile);
    5. fos.flush();
    6. System.out.println("successfully generated proxy class file");
    7. } catch (Exception e) {
    8. System.out.println("failed to generate proxy class file");
    9. }

    image.gif
    生成的类文件:

    1. public final class $Proxy0 extends Proxy implements Suitor {
    2. private static Method m1;
    3. private static Method m3;
    4. private static Method m2;
    5. private static Method m0;
    6. public $Proxy0(InvocationHandler var1) throws {
    7. super(var1);
    8. }
    9. public final boolean equals(Object var1) throws {
    10. try {
    11. return (Boolean)super.h.invoke(this, m1, new Object[]{var1});
    12. } catch (RuntimeException | Error var3) {
    13. throw var3;
    14. } catch (Throwable var4) {
    15. throw new UndeclaredThrowableException(var4);
    16. }
    17. }
    18. public final void sayHi(Beauty var1) throws {
    19. try {
    20. super.h.invoke(this, m3, new Object[]{var1});
    21. } catch (RuntimeException | Error var3) {
    22. throw var3;
    23. } catch (Throwable var4) {
    24. throw new UndeclaredThrowableException(var4);
    25. }
    26. }
    27. public final String toString() throws {
    28. try {
    29. return (String)super.h.invoke(this, m2, (Object[])null);
    30. } catch (RuntimeException | Error var2) {
    31. throw var2;
    32. } catch (Throwable var3) {
    33. throw new UndeclaredThrowableException(var3);
    34. }
    35. }
    36. public final int hashCode() throws {
    37. try {
    38. return (Integer)super.h.invoke(this, m0, (Object[])null);
    39. } catch (RuntimeException | Error var2) {
    40. throw var2;
    41. } catch (Throwable var3) {
    42. throw new UndeclaredThrowableException(var3);
    43. }
    44. }
    45. static {
    46. try {
    47. m1 = Class.forName("java.lang.Object").getMethod("equals", Class.forName("java.lang.Object"));
    48. m3 = Class.forName("com.wxy.popcorn.test.proxy.dynamic.Suitor").getMethod("sayHi", Class.forName("com.wxy.popcorn.test.proxy.dynamic.Beauty"));
    49. m2 = Class.forName("java.lang.Object").getMethod("toString");
    50. m0 = Class.forName("java.lang.Object").getMethod("hashCode");
    51. } catch (NoSuchMethodException var2) {
    52. throw new NoSuchMethodError(var2.getMessage());
    53. } catch (ClassNotFoundException var3) {
    54. throw new NoClassDefFoundError(var3.getMessage());
    55. }
    56. }
    57. }

    image.gif
    不难看出,代理类的私有静态字段维护了所有接口方法和从Object继承的方法。这些方法的调用最终都转移到InvocationHandler.invoke。