java中动态代理源码详解

在研究代码之前,我们先看看一个实例,然后我们根据实例来进行源码研究。

实例代码如下:

package com.jd.dynamicproxy.dynamicproxy;

import java.io.Serializable;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * Created by IntelliJ IDEA.
 * User: MessengerOfSpring
 * Date: 2017/12/3
 * Time: 21:39
 */


public class App {
    private interface Account {
        public Account deposit (double value);
        public double getBalance ();
    }

    private class ExampleInvocationHandler implements InvocationHandler {

        private double balance;

        @Override
        public Object invoke (Object proxy, Method method, Object[] args) throws Throwable {

            // simplified method checks, would need to check the parameter count and types too
            if ("deposit".equals(method.getName())) {
                Double value = (Double) args[0];
                System.out.println("deposit: " + value);
                balance += value;
                return proxy; // here we use the proxy to return 'this'
            }
            if ("getBalance".equals(method.getName())) {
                return balance;
            }
            return null;
        }
    }

    public static void main(String[] args) {
        new App();
    }

    public App() {
        //设置保存属性,用来将代理类字节码文件保存下来
        System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");
        
        Account account = (Account) Proxy.newProxyInstance( getClass().getClassLoader(), 
                                                            new Class[] {Account.class,Serializable.class},
                                                            new ExampleInvocationHandler());

        // method chaining for the win!
        account.deposit(5000).deposit(4000).deposit(-2500);
        System.out.println("Balance: " + account.getBalance());
    }

}

我们从Proxy中的public static Object newProxyInstance(ClassLoader loader,Class<?>[] interfaces,InvocationHandler h)函数开始讲起,这个函数的代码如下:

@CallerSensitive
    public static Object newProxyInstance(ClassLoader loader,
                                          Class<?>[] interfaces,
                                          InvocationHandler h)
        throws IllegalArgumentException
    {

        //判断h是否为null,如果为null的话就跑出NullPointerException异常
        Objects.requireNonNull(h);

       //将interfaces接口数组拷贝到intfs中

        final Class<?>[] intfs = interfaces.clone();

        //进行权限检查,关于这个可以查相关资料,这里不展开讲
        final SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            checkProxyAccess(Reflection.getCallerClass(), loader, intfs);
        }

        /*
         * 该方法先从缓存获取代理类, 如果没有再去生成一个代理类
         */
        Class<?> cl = getProxyClass0(loader, intfs);

        /*
         * Invoke its constructor with the designated invocation handler.
         */
        try {
            if (sm != null) {
                checkNewProxyPermission(Reflection.getCallerClass(), cl);
            }

            //

            final Constructor<?> cons = cl.getConstructor(constructorParams);
            final InvocationHandler ih = h;
            if (!Modifier.isPublic(cl.getModifiers())) {
                AccessController.doPrivileged(new PrivilegedAction<Void>() {
                    public Void run() {
                        cons.setAccessible(true);
                        return null;
                    }
                });
            }
            return cons.newInstance(new Object[]{h});
        } catch (IllegalAccessException|InstantiationException e) {
            throw new InternalError(e.toString(), e);
        } catch (InvocationTargetException e) {
            Throwable t = e.getCause();
            if (t instanceof RuntimeException) {
                throw (RuntimeException) t;
            } else {
                throw new InternalError(t.toString(), t);
            }
        } catch (NoSuchMethodException e) {
            throw new InternalError(e.toString(), e);
        }
    }

我们开始解析getProxyClass0函数,这个函数用来创建一个代理类对象,代码如下:

/**
     * Generate a proxy class.  Must call the checkProxyAccess method
     * to perform permission checks before calling this.
     */
    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

        //如果缓存中存在代理类对象,那么就直接返回,否则就会调用ProxyClassFactory这个工厂去生成一个代理类。
        return proxyClassCache.get(loader, interfaces);
    }

我们现在进入proxyClassCache.get函数中(proxyClassCache类对象的创建代码如下:

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

KeyFactory实现BiFunction<ClassLoader, Class<?>[], Object>,ProxyClassFactory实现BiFunction<ClassLoader, Class<?>[], Class<?>>。

其中KeyFactory的代码如下:

/**
     * A function that maps an array of interfaces to an optimal key where
     * Class objects representing interfaces are weakly referenced.
     */
    private static final class KeyFactory
        implements BiFunction<ClassLoader, Class<?>[], Object>
    {
        @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);
            }
        }
    }

ProxyClassFactory类代码如下:

/**
     * A factory function that generates, defines and returns the proxy class given
     * the ClassLoader and array of interfaces.
     */
    private static final class ProxyClassFactory
        implements BiFunction<ClassLoader, Class<?>[], Class<?>>
    {
        // prefix for all proxy class names
        private static final String proxyClassNamePrefix = "$Proxy";

        // next number to use for generation of unique proxy class names
        private static final AtomicLong nextUniqueNumber = new AtomicLong();

        @Override
        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());
            }
        }
    }

上面两个类我们后面再讲,在进入到proxyClassCache.get(loader, interfaces)的get函数前,我们先看看它的构造函数和成员变量,它们所在的类为WeakCache,代码如下:   

//Reference引用队列

    private final ReferenceQueue<K> refQueue = new ReferenceQueue<>();
    // the key type is Object for supporting null key

   //缓存的底层实现, key为一级缓存, value为二级缓存。 为了支持null, map的key类型设置为Object
    private final ConcurrentMap<Object, ConcurrentMap<Object, Supplier<V>>> map = new ConcurrentHashMap<>();

   //reverseMap记录了所有代理类生成器是否可用, 这是为了实现缓存的过期机制
    private final ConcurrentMap<Supplier<V>, Boolean> reverseMap = new ConcurrentHashMap<>();

    //生成二级缓存key的工厂, 这里传入的是KeyFactory
    private final BiFunction<K, P, ?> subKeyFactory;

    //生成二级缓存value的工厂, 这里传入的是ProxyClassFactory
    private final BiFunction<K, P, V> valueFactory;

    /**
     * Construct an instance of {@code WeakCache}
     *
     * @param subKeyFactory a function mapping a pair of
     *                      {@code (key, parameter) -> sub-key}
     * @param valueFactory  a function mapping a pair of
     *                      {@code (key, parameter) -> value}
     * @throws NullPointerException if {@code subKeyFactory} or
     *                              {@code valueFactory} is null.
     */

    //构造器, 传入生成二级缓存key的工厂和生成二级缓存value的工厂​​​​​​​
    public WeakCache(BiFunction<K, P, ?> subKeyFactory,
                     BiFunction<K, P, V> valueFactory) {
        this.subKeyFactory = Objects.requireNonNull(subKeyFactory);
        this.valueFactory = Objects.requireNonNull(valueFactory);
    }

proxyClassCache.get(loader, interfaces)中get代码如下:

/**
     * Look-up the value through the cache. This always evaluates the
     * {@code subKeyFactory} function and optionally evaluates
     * {@code valueFactory} function if there is no entry in the cache for given
     * pair of (key, subKey) or the entry has already been cleared.
     *
     * @param key       possibly null key
     * @param parameter parameter used together with key to create sub-key and
     *                  value (should not be null)
     * @return the cached value (never null)
     * @throws NullPointerException if {@code parameter} passed in or
     *                              {@code sub-key} calculated by
     *                              {@code subKeyFactory} or {@code value}
     *                              calculated by {@code valueFactory} is null.
     */
    public V get(K key, P parameter) {
        Objects.requireNonNull(parameter);

        //清除过期的缓存

        expungeStaleEntries();

       //将ClassLoader包装成CacheKey, 作为一级缓存的key,其中cacheKey中的referent成员变量值为key,queue成员变量为refQueue

       Object cacheKey = CacheKey.valueOf(key, refQueue);

        // lazily install the 2nd level valuesMap for the particular cacheKey
        //获取得到二级缓存

        ConcurrentMap<Object, Supplier<V>> valuesMap = map.get(cacheKey);
        //如果根据ClassLoader没有获取到对应的值

        if (valuesMap == null) {

            //以CAS方式放入, 如果不存在则放入,否则返回原先的值
            ConcurrentMap<Object, Supplier<V>> oldValuesMap = map.putIfAbsent(cacheKey, valuesMap = new ConcurrentHashMap<>());
           //如果oldValuesMap有值, 说明放入失败,即cacheKey存在(至于为什么可以去看看putIfAbsent这个方法),否则cacheKey不存在

           if (oldValuesMap != null) {
                valuesMap = oldValuesMap;
            }
        }

        // create subKey and retrieve the possible Supplier<V> stored by that
        // subKey from valuesMap

        //根据代理类实现的接口数组来生成二级缓存key, 分为key0, key1, key2, keyx,这里apply调用的是KeyFactory类中的,返回Key2类型对          //象,其中parameter中两个接口,其中第一个存储到Key2中的referent成员变量,第二个在此基础上创建一个新的WeakReference类对            //象中,这个类对象中的referent成员变量为第二个接口。
        Object subKey = Objects.requireNonNull(subKeyFactory.apply(key, parameter));

        //这里通过subKey获取到二级缓存的值
        Supplier<V> supplier = valuesMap.get(subKey);
        Factory factory = null;

        while (true) {

            //如果通过subKey取出来的值不为空
            if (supplier != null) {
                // supplier might be a Factory or a CacheValue<V> instance

               //在这里supplier可能是一个Factory也可能会是一个CacheValue,在这里不作判断, 而是在Supplier实现类的get方法里面进行验证
                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实例作为subKey对应的值
                factory = new Factory(key, parameter, subKey, valuesMap);
            }

            if (supplier == null) {

                //到这里表明subKey没有对应的值, 就将factory作为subKey的值放入
                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);
                }
            }
        }
    }

进入Factory类,代码如下:

/**
     * A factory {@link Supplier} that implements the lazy synchronized
     * construction of the value and installment of it into the cache.
     */
    private final class Factory implements Supplier<V> {

        //一级缓存key, 根据ClassLoader生成

        private final K key;

        //代理类实现的接口数组
        private final P parameter;

        //二级缓存key, 根据接口数组生成
        private final Object subKey;

        //二级缓存
        private final ConcurrentMap<Object, Supplier<V>> valuesMap;

        Factory(K key, P parameter, Object subKey,
                ConcurrentMap<Object, Supplier<V>> valuesMap) {
            this.key = key;
            this.parameter = parameter;
            this.subKey = subKey;
            this.valuesMap = valuesMap;
        }

        @Override
        public synchronized V get() { // serialize access
            //这里再一次去二级缓存里面获取Supplier, 用来验证是否是Factory本身
            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

                //在这里验证supplier是否是Factory实例本身, 如果不则返回null让调用者继续轮询重试 

                //期间supplier可能替换成了CacheValue, 或者由于生成代理类失败被从二级缓存中移除了
                return null;
            }
            // else still us (supplier == this)

            // create new value
            V value = null;
            try {

                //委托valueFactory去生成代理类, 这里会通过传入的ProxyClassFactory去生成代理类
                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

            //只有value的值不为空才能到达这里​​​​​​​
            assert value != null;

            // wrap value with CacheValue (WeakReference)

            //使用弱引用包装生成的代理类
            CacheValue<V> cacheValue = new CacheValue<>(value);

            // put into reverseMap

            //对cacheValue进行标记
            reverseMap.put(cacheValue, Boolean.TRUE);

            // try replacing us with CacheValue (this should always succeed)

            //将包装后的cacheValue放入二级缓存中, 这个操作必须成功, 否则就报错​​​​​​​
            if (!valuesMap.replace(subKey, this, cacheValue)) {
                throw new AssertionError("Should not reach here");
            }

            // successfully replaced us with new CacheValue -> return the value
            // wrapped by it
            return value;
        }
    }

流程如下:

相关流程图
标题

接下来我们进入ProxyClassFactory类中的apply函数中,相关代码如下:

/**
     * A factory function that generates, defines and returns the proxy class given
     * the ClassLoader and array of interfaces.
     */
    private static final class ProxyClassFactory
        implements BiFunction<ClassLoader, Class<?>[], Class<?>>
    {
        // prefix for all proxy class names

        //代理类名称前缀
        private static final String proxyClassNamePrefix = "$Proxy";

        // next number to use for generation of unique proxy class names

        //采用一个原子类对象,用来生成一个计数,这个计数用来拼成代理类对象名称
        private static final AtomicLong nextUniqueNumber = new AtomicLong();

        @Override

        //loader为加载器类对象,interfaces为接口数组
        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 {

                    //通过loader加载器获取到接口对应的Class类对象
                    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.
                 */

                //将该接口的Class类对象保存到map容器interfaceSet中
                if (interfaceSet.put(interfaceClass, Boolean.TRUE) != null) {
                    throw new IllegalArgumentException(
                        "repeated interface: " + interfaceClass.getName());
                }
            }

            //整个循环下来,将所有的接口的Class类对象都保存在了interfaceSet中

            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();

                //如果该接口不为public
                if (!Modifier.isPublic(flags)) {
                    accessFlags = Modifier.FINAL;

                    //返回接口名称(例如String.class.getName()获得java.lang.String)
                    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)) {
                        //走到这里说明有些接口不在同一个包中,也就是这些接口要么都是public,要么都不为public且要在同一个包中。
                        throw new IllegalArgumentException(
                            "non-public interfaces from different packages");
                    }
                }
            }

           //如果proxyPkg为null,那么就采用默认的包名称

            if (proxyPkg == null) {
                // if no non-public proxy interfaces, use com.sun.proxy package

                //此时proxyPkg为com.sun.proxy.
                proxyPkg = ReflectUtil.PROXY_PACKAGE + ".";
            }

            /*
             * Choose a name for the proxy class to generate.
             */

            //获取一个唯一计数值
            long num = nextUniqueNumber.getAndIncrement();

            //拼成代理类名称,如果num为0且在默认包的情况下那么proxyName为com.sun.proxy.$Proxy0
            String proxyName = proxyPkg + proxyClassNamePrefix + num;

            /*
             * Generate the specified proxy class.
             */

            //开始针对该代理类名称获取相应的class字节码内容
            byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
                proxyName, interfaces, accessFlags);
            try {

                //根据该字节码内容生成一个对应的Class类对象。
                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());
            }
        }
    }

接下来我们进入到ProxyGenerator.generateProxyClass(proxyName, interfaces, accessFlags)函数中,代码如下:

public static byte[] generateProxyClass(String s, Class aclass[], int i)
    {
        ProxyGenerator proxygenerator = new ProxyGenerator(s, aclass, i);

        //生成Class字节码内容
        byte abyte0[] = proxygenerator.generateClassFile();

  //判断是否要将该字节码内容保存到文件中,

 //我们在实例代码中添加System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");就可以将字节码保   //存到相应的文件中
        if(saveGeneratedFiles)
            AccessController.doPrivileged(new PrivilegedAction(s, abyte0) {

                public Void run()
                {
                    try
                    {
                        int j = name.lastIndexOf('.');
                        Path path;
                        if(j > 0)
                        {
                            Path path1 = Paths.get(name.substring(0, j).replace('.', File.separatorChar), new String[0]);
                            Files.createDirectories(path1, new FileAttribute[0]);
                            path = path1.resolve((new StringBuilder()).append(name.substring(j + 1, name.length())).append(".class").toString());
                        } else
                        {
                            path = Paths.get((new StringBuilder()).append(name).append(".class").toString(), new String[0]);
                        }
                        Files.write(path, classFile, new OpenOption[0]);
                        return null;
                    }
                    catch(IOException ioexception)
                    {
                        throw new InternalError((new StringBuilder()).append("I/O exception saving generated file: ").append(ioexception).toString());
                    }
                }

                public volatile Object run()
                {
                    return run();
                }

                final String val$name;
                final byte val$classFile[];

            
            {
                name = s;
                classFile = abyte0;
                super();
            }
            }
);

        //如果不用保存,那么就直接返回字节码内容
        return abyte0;
    }

接下来我们开始分析defineClass0(loader, proxyName,proxyClassFile, 0, proxyClassFile.length);函数,这是一个native方法,负责字节码加载的实现,并返回对应的Class对象。根据上面的例子,我们得到的代理类字节码文件结构如下:

经过反编译后,代码如下:

package com.jd.dynamicproxy.dynamicproxy;

import java.io.Serializable;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.lang.reflect.UndeclaredThrowableException;

final class $Proxy0 extends Proxy
  implements App.Account, Serializable
{
  private static Method m1;
  private static Method m4;
  private static Method m2;
  private static Method m3;
  private static Method m0;

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

  public final boolean equals(Object paramObject)
    throws 
  {
    try
    {
      return ((Boolean)this.h.invoke(this, m1, new Object[] { paramObject })).booleanValue();
    }
    catch (RuntimeException localRuntimeException)
    {
      throw localRuntimeException;
    }
    catch (Throwable localThrowable)
    {
    }
    throw new UndeclaredThrowableException(localThrowable);
  }

  public final double getBalance()
    throws 
  {
    try
    {
      return ((Double)this.h.invoke(this, m4, null)).doubleValue();
    }
    catch (RuntimeException localRuntimeException)
    {
      throw localRuntimeException;
    }
    catch (Throwable localThrowable)
    {
    }
    throw new UndeclaredThrowableException(localThrowable);
  }

  public final String toString()
    throws 
  {
    try
    {
      return (String)this.h.invoke(this, m2, null);
    }
    catch (RuntimeException localRuntimeException)
    {
      throw localRuntimeException;
    }
    catch (Throwable localThrowable)
    {
    }
    throw new UndeclaredThrowableException(localThrowable);
  }

  public final App.Account deposit(double paramDouble)
    throws 
  {
    try
    {
      return (Serializable)this.h.invoke(this, m3, new Object[] { Double.valueOf(paramDouble) });
    }
    catch (RuntimeException localRuntimeException)
    {
      throw localRuntimeException;
    }
    catch (Throwable localThrowable)
    {
    }
    throw new UndeclaredThrowableException(localThrowable);
  }

  public final int hashCode()
    throws 
  {
    try
    {
      return ((Integer)this.h.invoke(this, m0, null)).intValue();
    }
    catch (RuntimeException localRuntimeException)
    {
      throw localRuntimeException;
    }
    catch (Throwable localThrowable)
    {
    }
    throw new UndeclaredThrowableException(localThrowable);
  }

  static
  {
    try
    {
      m1 = Class.forName("java.lang.Object").getMethod("equals", new Class[] { Class.forName("java.lang.Object") });
      m4 = Class.forName("com.jd.dynamicproxy.dynamicproxy.App$Account").getMethod("getBalance", new Class[0]);
      m2 = Class.forName("java.lang.Object").getMethod("toString", new Class[0]);
      m3 = Class.forName("com.jd.dynamicproxy.dynamicproxy.App$Account").getMethod("deposit", new Class[] { Double.TYPE });
      m0 = Class.forName("java.lang.Object").getMethod("hashCode", new Class[0]);
      return;
    }
    catch (NoSuchMethodException localNoSuchMethodException)
    {
      throw new NoSuchMethodError(localNoSuchMethodException.getMessage());
    }
    catch (ClassNotFoundException localClassNotFoundException)
    {
    }
    throw new NoClassDefFoundError(localClassNotFoundException.getMessage());
  }
}

从中可以看到,该代理类继承了Proxy类且实现了相关的接口,你调用接口方法都会去调用InvocationHandler实现类中的invoke函数,Proxy中有m0、m1、m2、m3、m4五个Method类对象,其中包括了实现接口的。在调用invoke函数的时候会将相应的Method类对象作为参数传入,从而实现代理的功能。

参考文章文章1文章2文章3

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值