概念

JDK动态代理与静态代理是相对的,静态代理是在编译期就确定了代理类和被代理类的关系,且生成代理类。而且静态代理要求被代理的接口必须有其实现,因为代理类实现接口方法实际上是调用接口实现类的方法实现的。而动态代理是在运行期利用JVM的反射机制生成代理类,这里是直接生成类的字节码,然后通过类加载器载入JAVA虚拟机执行。

demo

不做赘述,直接上demo。

  • 被代理类接口

    public interface ISubject {
        void doSomething();
    }
  • 被代理类实现

    public class SubjectImpl implements ISubject {
    
        @Override
        public void doSomething() {
            System.out.println("doSomething...");
        }
    }
  • InvocationHandler工具类

    import java.lang.reflect.InvocationHandler;
    import java.lang.reflect.Method;
    import java.lang.reflect.Proxy;
    
    public class JDKDynamicProxy implements InvocationHandler{
    
        private Object target;
    
        public JDKDynamicProxy(){
        }
    
        public JDKDynamicProxy(Object target){
            this.target=target;
        }
    
        public <T>T getProxy(){
            System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");
            // return (T) Proxy.newProxyInstance(target.getClass().getClassLoader(),target.getClass().getInterfaces(),this);
            return (T) Proxy.newProxyInstance(target.getClass().getClassLoader(),target.getClass().getInterfaces(),this);
        }
    
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            System.out.println("before...");
            Object result=method.invoke(target,args);
            System.out.println("after...");
            return result;
        }
    }
  • 测试类

    public class TestProxy {
    
        public static void main(String[] args) {
            System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles","true");
    
            ISubject subject=new JDKDynamicProxy(new SubjectImpl()).getProxy();
            //ISubject subject= (ISubject) Proxy.newProxyInstance(subjectImpl.getClass().getClassLoader(),subjectImpl.getClass().getInterfaces(),new JDKDynamicProxy(subjectImpl));
            //ISubject subject= (ISubject) Proxy.newProxyInstance(ISubject.class.getClassLoader(),new Class[]{ISubject.class},new JDKDynamicProxy(subjectImpl));
            subject.doSomething();
        }
    }
  • 运行结果

    before...
    doSomething...
    after...
  • 生成的代理类文件

    //
    // Source code recreated from a .class file by IntelliJ IDEA
    // (powered by Fernflower decompiler)
    //
    
    package com.sun.proxy;
    
    import java.lang.reflect.InvocationHandler;
    import java.lang.reflect.Method;
    import java.lang.reflect.Proxy;
    import java.lang.reflect.UndeclaredThrowableException;
    
    public final class $Proxy0 extends Proxy implements ISubject {
        private static Method m1;
        private static Method m3;
        private static Method m2;
        private static Method m0;
    
        public $Proxy0(InvocationHandler var1) throws  {
            super(var1);
        }
    
        public final boolean equals(Object var1) throws  {
            try {
                return (Boolean)super.h.invoke(this, m1, new Object[]{var1});
            } catch (RuntimeException | Error var3) {
                throw var3;
            } catch (Throwable var4) {
                throw new UndeclaredThrowableException(var4);
            }
        }
    
        public final void doSomething() throws  {
            try {
                super.h.invoke(this, m3, (Object[])null);
            } catch (RuntimeException | Error var2) {
                throw var2;
            } catch (Throwable var3) {
                throw new UndeclaredThrowableException(var3);
            }
        }
    
        public final String toString() throws  {
            try {
                return (String)super.h.invoke(this, m2, (Object[])null);
            } catch (RuntimeException | Error var2) {
                throw var2;
            } catch (Throwable var3) {
                throw new UndeclaredThrowableException(var3);
            }
        }
    
        public final int hashCode() throws  {
            try {
                return (Integer)super.h.invoke(this, m0, (Object[])null);
            } catch (RuntimeException | Error var2) {
                throw var2;
            } catch (Throwable var3) {
                throw new UndeclaredThrowableException(var3);
            }
        }
    
        static {
            try {
                m1 = Class.forName("java.lang.Object").getMethod("equals", Class.forName("java.lang.Object"));
                m3 = Class.forName("ISubject").getMethod("doSomething");
                m2 = Class.forName("java.lang.Object").getMethod("toString");
                m0 = Class.forName("java.lang.Object").getMethod("hashCode");
            } catch (NoSuchMethodException var2) {
                throw new NoSuchMethodError(var2.getMessage());
            } catch (ClassNotFoundException var3) {
                throw new NoClassDefFoundError(var3.getMessage());
            }
        }
    }

原理

流程

  • 获取代理类——调用Proxy.newProxyInstance

    1. 获取代理类的Class实例

      getProxyClass0(loader, intfs)

    2. 获取代理类实例的构造方法,并确保其访问权限

      final Constructor<?> cons = cl.getConstructor(constructorParams)

    3. 利用反射机制调用构造方法,返回代理类实例,参数是调用Proxy.newProxyInstance时传进来的InvocationHandler实例h 。

      cons.newInstance(new Object[]{h})

  • 方法实现

    前面利用反射机制调用代理类的构造方法时传入了InvocationHandler实例h ,代理类$Proxy0的构造方法如下:

    public $Proxy0(InvocationHandler var1) throws  {
        super(var1);
    }

    这是调用父类的构造函数,并传入参数h。

    所以在获取到代理类实例并执行方法时如测试类的subject.doSomething(),实际调用的是代理类内的doSomething(),如下所示。

    public final void doSomething() throws  {
        try {
            super.h.invoke(this, m3, (Object[])null);
        } catch (RuntimeException | Error var2) {
            throw var2;
        } catch (Throwable var3) {
            throw new UndeclaredThrowableException(var3);
        }
    }

    所以JDK动态代理的接口方法实现逻辑是完全由InvocationHandler实例的invoke方法决定的 。

获取代理类的Class实例探究

  • getProxyClass0(loader, intfs)方法

    private static Class<?> getProxyClass0(ClassLoader loader,
                                           Class<?>... interfaces) {
        if (interfaces.length > 65535) {
            throw new IllegalArgumentException("interface limit exceeded");
        }
    
        // If the proxy class defined by the given loader implementing
        // the given interfaces exists, this will simply return the cached copy;
        // otherwise, it will create the proxy class via the ProxyClassFactory
        return proxyClassCache.get(loader, interfaces);
    }

    在Proxy类getProxyClass0(loader, intfs)方法中并无核心代码,主要是方法最后一行去缓存对象中获取代理类实例。

  • java.lang.reflect.WeakCache 类

    private static final WeakCache<ClassLoader, Class<?>[], Class<?>>
       proxyClassCache = new WeakCache<>(new KeyFactory(), new ProxyClassFactory());

    proxyClassCache是Proxy类的静态变量,调用WeakCache类的构造函数初始化时,传入keyFactoryproxyClassFactory两个实例。注意WeakCache对象的数据结构包含两级键值。接下来就进入WeakCache类的get方法查看一番。

  • WeakCache类

    • get方法代码

      public V get(K key, P parameter) {
          Objects.requireNonNull(parameter);
      
          expungeStaleEntries();
      
          Object cacheKey = CacheKey.valueOf(key, refQueue);
      
          // lazily install the 2nd level valuesMap for the particular cacheKey
          ConcurrentMap<Object, Supplier<V>> valuesMap = map.get(cacheKey);
          if (valuesMap == null) {
              ConcurrentMap<Object, Supplier<V>> oldValuesMap
                  = map.putIfAbsent(cacheKey,
                                    valuesMap = new ConcurrentHashMap<>());
              if (oldValuesMap != null) {
                  valuesMap = oldValuesMap;
              }
          }
      
          // create subKey and retrieve the possible Supplier<V> stored by that
          // subKey from valuesMap
          Object subKey = Objects.requireNonNull(subKeyFactory.apply(key, parameter));
          Supplier<V> supplier = valuesMap.get(subKey);
          Factory factory = null;
      
          while (true) {
              if (supplier != null) {
                  // supplier might be a Factory or a CacheValue<V> instance
                  V value = supplier.get();
                  if (value != null) {
                      return value;
                  }
              }
              // else no supplier in cache
              // or a supplier that returned null (could be a cleared CacheValue
              // or a Factory that wasn't successful in installing the CacheValue)
      
              // lazily construct a Factory
              if (factory == null) {
                  factory = new Factory(key, parameter, subKey, valuesMap);
              }
      
              if (supplier == null) {
                  supplier = valuesMap.putIfAbsent(subKey, factory);
                  if (supplier == null) {
                      // successfully installed Factory
                      supplier = factory;
                  }
                  // else retry with winning supplier
              } else {
                  if (valuesMap.replace(subKey, supplier, factory)) {
                      // successfully replaced
                      // cleared CacheEntry / unsuccessful Factory
                      // with our Factory
                      supplier = factory;
                  } else {
                      // retry with current supplier
                      supplier = valuesMap.get(subKey);
                  }
              }
          }
      }
    • get方法核心代码解释

      获取一级和二级键。

      //根据类加载器计算一级键 cacheKey=f(loader);
      Object cacheKey = CacheKey.valueOf(key, refQueue);
      
      //根据接口计算二级键 subKey=g(interfaces);
      Object subKey = Objects.requireNonNull(subKeyFactory.apply(key, parameter));

      注意这里的subKeyFactory是Proxy初始化WeakCache类对象proxyClassCache时的入参new KeyFactory();KeyFactory是Proxy的内部类。不妨进入apply简单看一下:

      @Override
      public Object apply(ClassLoader classLoader, Class<?>[] interfaces) {
          switch (interfaces.length) {
              case 1: return new Key1(interfaces[0]); // the most frequent
              case 2: return new Key2(interfaces[0], interfaces[1]);
              case 0: return key0;
              default: return new KeyX(interfaces);
          }
      }

      循环

      ​ 接下来是一个while循环,第一次循环前factory和supplier都为null ,所以循环体内只是做了一些初始化的工作,并将factory赋值给了supplier(Factory类是WeakCache的内部类,且继承了Supplier类)。

      第二次循环时,执行V value = supplier.get(),实际上就是调用factory.get()方法获取动态代理类的Class实例 。

    • factory.get()方法

      方法完整代码如下:

      @Override
      public synchronized V get() { // serialize access
          // re-check
          Supplier<V> supplier = valuesMap.get(subKey);
          if (supplier != this) {
              // something changed while we were waiting:
              // might be that we were replaced by a CacheValue
              // or were removed because of failure ->
              // return null to signal WeakCache.get() to retry
              // the loop
              return null;
          }
          // else still us (supplier == this)
      
          // create new value
          V value = null;
          try {
              value = Objects.requireNonNull(valueFactory.apply(key, parameter));
          } finally {
              if (value == null) { // remove us on failure
                  valuesMap.remove(subKey, this);
              }
          }
          // the only path to reach here is with non-null value
          assert value != null;
      
          // wrap value with CacheValue (WeakReference)
          CacheValue<V> cacheValue = new CacheValue<>(value);
      
          // try replacing us with CacheValue (this should always succeed)
          if (valuesMap.replace(subKey, this, cacheValue)) {
              // put also in reverseMap
              reverseMap.put(cacheValue, Boolean.TRUE);
          } else {
              throw new AssertionError("Should not reach here");
          }
      
          // successfully replaced us with new CacheValue -> return the value
          // wrapped by it
          return value;
      }

      第4行代码Supplier<V> supplier = valuesMap.get(subKey)通过subKey获取方才的supplier也就是factory。然后在第18行调用了valueFactory.apply方法创建动态代理类并将结果赋值给变量value。 valueFactory是初始化WeakCache对象调用构造方法时传入的参数 即Prxoy的内部类ProxyClassFactory对象。

  • ProxyClassFactory类

    进入apply方法

    public Class<?> apply(ClassLoader loader, Class<?>[] interfaces) {
    
        Map<Class<?>, Boolean> interfaceSet = new IdentityHashMap<>(interfaces.length);
        for (Class<?> intf : interfaces) {
            /*
                     * Verify that the class loader resolves the name of this
                     * interface to the same Class object.
                     */
            Class<?> interfaceClass = null;
            try {
                interfaceClass = Class.forName(intf.getName(), false, loader);
            } catch (ClassNotFoundException e) {
            }
            if (interfaceClass != intf) {
                throw new IllegalArgumentException(
                    intf + " is not visible from class loader");
            }
            /*
                     * Verify that the Class object actually represents an
                     * interface.
                     */
            if (!interfaceClass.isInterface()) {
                throw new IllegalArgumentException(
                    interfaceClass.getName() + " is not an interface");
            }
            /*
                     * Verify that this interface is not a duplicate.
                     */
            if (interfaceSet.put(interfaceClass, Boolean.TRUE) != null) {
                throw new IllegalArgumentException(
                    "repeated interface: " + interfaceClass.getName());
            }
        }
    
        String proxyPkg = null;     // package to define proxy class in
        int accessFlags = Modifier.PUBLIC | Modifier.FINAL;
    
        /*
                 * Record the package of a non-public proxy interface so that the
                 * proxy class will be defined in the same package.  Verify that
                 * all non-public proxy interfaces are in the same package.
                 */
        for (Class<?> intf : interfaces) {
            int flags = intf.getModifiers();
            if (!Modifier.isPublic(flags)) {
                accessFlags = Modifier.FINAL;
                String name = intf.getName();
                int n = name.lastIndexOf('.');
                String pkg = ((n == -1) ? "" : name.substring(0, n + 1));
                if (proxyPkg == null) {
                    proxyPkg = pkg;
                } else if (!pkg.equals(proxyPkg)) {
                    throw new IllegalArgumentException(
                        "non-public interfaces from different packages");
                }
            }
        }
    
        if (proxyPkg == null) {
            // if no non-public proxy interfaces, use com.sun.proxy package
            proxyPkg = ReflectUtil.PROXY_PACKAGE + ".";
        }
    
        /*
                 * Choose a name for the proxy class to generate.
                 */
        long num = nextUniqueNumber.getAndIncrement();
        String proxyName = proxyPkg + proxyClassNamePrefix + num;
    
        /*
                 * Generate the specified proxy class.
                 */
        byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
            proxyName, interfaces, accessFlags);
        try {
            return defineClass0(loader, proxyName,
                                proxyClassFile, 0, proxyClassFile.length);
        } catch (ClassFormatError e) {
            /*
                     * A ClassFormatError here means that (barring bugs in the
                     * proxy class generation code) there was some other
                     * invalid aspect of the arguments supplied to the proxy
                     * class creation (such as virtual machine limitations
                     * exceeded).
                     */
            throw new IllegalArgumentException(e.toString());
        }
    }

    该方法前边包括一些校验、计算出访问标志和包名、代理类定名 ,然后在73行创建代理类的字节码文件,并defineClass0将字节码文件加载到虚拟机和返回代理类的Class实例。

如上就是第一次创建代理类的大致流程。

参考文献: JDK动态代理