JDK動態代理步驟詳解(源碼分析)

動態代理步驟

1.創建一個實現接口InvocationHandler的類,它必須實現invoke方法

2.創建被代理的類以及接口

3.通過Proxy的靜態方法

通過Proxy的靜態方法

ProxyObject proxyObject = new ProxyObject();
    InvocationHandler invocationHandler = new DynamicProxy(proxyObject);
    ClassLoader classLoader = proxyObject.getClass().getClassLoader();
    ProxyObjectInterface proxy = (IRoom) Proxy.newProxyInstance(classLoader,new Class[]
    {ProxyObjectInterface.class},invocationHandler);
    proxy.execute();

    public class DynamicProxy implements InvocationHandler {
    private Object object;

    public DynamicProxy(Object object){
        this.object = object;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object result = method.invoke(object,args);
        return result;
    }
}

創建一個代理 newProxyInstance

public static Object newProxyInstance(ClassLoader loader,
                                          Class<?>[] interfaces,
                                          InvocationHandler h)
        throws IllegalArgumentException
    {
        //檢驗h不為空,h為空拋異常
        Objects.requireNonNull(h);
        //接口的類對象拷貝一份
        final Class<?>[] intfs = interfaces.clone();
        //進行一些安全性檢查
        final SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            checkProxyAccess(Reflection.getCallerClass(), loader, intfs);
        }
        /*
         * Look up or generate the designated proxy class.
         *  查詢(在緩存中已經有)或生成指定的代理類的class對象。
         */
        Class<?> cl = getProxyClass0(loader, intfs);
        /*
         * Invoke its constructor with the designated invocation handler.
         */
        try {
            if (sm != null) {
                checkNewProxyPermission(Reflection.getCallerClass(), cl);
            }
            //得到代理類對象的構造函數,這個構造函數的參數由constructorParams指定
            //參數constructorParames為常量值:
            private static final Class<?>[] constructorParams = { InvocationHandler.class };
            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;
                    }
                });
            }
            //這裡生成代理對象,傳入的參數new Object[]{h}後面講
            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);
        }
    }

先對h進行判空處理。
這段代碼核心就是通過getProxyClass0(loader, intfs)得到代理類的Class對象,然後通過Class對象得到構造方法,進而創建代理對象。下一步看getProxyClass0這個方法。從1可知,先接口得到接口類,當接口的數量超過65535,則報異常。

//此方法也是Proxy類下的方法
    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
        //意思是:如果代理類被指定的類加載器loader定義瞭,並實現瞭給定的接口interfaces,
        //那麼就返回緩存的代理類對象,否則使用ProxyClassFactory創建代理類。
        return proxyClassCache.get(loader, interfaces);
    }

proxyClassCache 是一個弱引用的緩存
這裡看到proxyClassCache,有Cache便知道是緩存的意思,正好呼應瞭前面Look up or generate the designated proxy class。查詢(在緩存中已經有)或生成指定的代理類的class對象這段註釋。

在進入get方法之前,我們看下 proxyClassCache是什麼?高能預警,前方代碼看起來可能有亂,但我們隻需要關註重點即可。

private static final WeakCache<ClassLoader, Class<?>[], Class<?>>
        proxyClassCache = new WeakCache<>(new KeyFactory(), new ProxyClassFactory());
//K代表key的類型,P代表參數的類型,V代表value的類型。
// WeakCache<ClassLoader, Class<?>[], Class<?>>  proxyClassCache  說明proxyClassCache存的值是Class<?>對象,正是我們需要的代理類對象。
final class WeakCache<K, P, V> {
    private final ReferenceQueue<K> refQueue
        = new ReferenceQueue<>();
    // the key type is Object for supporting null key
    private final ConcurrentMap<Object, ConcurrentMap<Object, Supplier<V>>> map
        = new ConcurrentHashMap<>();
    private final ConcurrentMap<Supplier<V>, Boolean> reverseMap
        = new ConcurrentHashMap<>();
    private final BiFunction<K, P, ?> subKeyFactory;
    private final BiFunction<K, P, V> valueFactory;
    public WeakCache(BiFunction<K, P, ?> subKeyFactory,
                     BiFunction<K, P, V> valueFactory) {
        this.subKeyFactory = Objects.requireNonNull(subKeyFactory);
        this.valueFactory = Objects.requireNonNull(valueFactory);
    }

其中map變量是實現緩存的核心變量,他是一個雙重的Map結構: (key, sub-key) -> value。其中key是傳進來的Classloader進行包裝後的對象,sub-key是由WeakCache構造函數傳人的KeyFactory()生成的。value就是產生代理類的對象,是由WeakCache構造函數傳人的ProxyClassFactory()生成的。如下,回顧一下:

proxyClassCache是個WeakCache類的對象,調用proxyClassCache.get(loader, interfaces); 可以得到緩存的代理類或創建代理類(沒有緩存的情況)。

說明WeakCache中有get這個方法。先看下WeakCache類的定義(這裡先隻給出變量的定義和構造函數),繼續看它的get();

//K和P就是WeakCache定義中的泛型,key是類加載器,parameter是接口類數組
public V get(K key, P parameter) {
        //檢查parameter不為空
        Objects.requireNonNull(parameter);
         //清除無效的緩存
        expungeStaleEntries();
        // cacheKey就是(key, sub-key) -> value裡的一級key,
        Object cacheKey = CacheKey.valueOf(key, refQueue);
        // lazily install the 2nd level valuesMap for the particular cacheKey
        //根據一級key得到 ConcurrentMap<Object, Supplier<V>>對象。如果之前不存在,則新建一個ConcurrentMap<Object, Supplier<V>>和cacheKey(一級key)一起放到map中。
        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
        //這部分就是調用生成sub-key的代碼,上面我們已經看過怎麼生成的瞭
        Object subKey = Objects.requireNonNull(subKeyFactory.apply(key, parameter));
        //通過sub-key得到supplier
        Supplier<V> supplier = valuesMap.get(subKey);
        //supplier實際上就是這個factory
        Factory factory = null;

        while (true) {
            //如果緩存裡有supplier ,那就直接通過get方法,得到代理類對象,返回,就結束瞭,一會兒分析get方法。
            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
            //下面的所有代碼目的就是:如果緩存中沒有supplier,則創建一個Factory對象,把factory對象在多線程的環境下安全的賦給supplier。
            //因為是在while(true)中,賦值成功後又回到上面去調get方法,返回才結束。
            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);
                }
            }
        }
    }

所以接下來我們看Factory類中的get方法。接下來看supplier的get()

public synchronized V get() { // serialize access
            // re-check
            Supplier<V> supplier = valuesMap.get(subKey);
            //重新檢查得到的supplier是不是當前對象
            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 {
                 //代理類就是在這個位置調用valueFactory生成的
                 //valueFactory就是我們傳入的 new ProxyClassFactory()
                //一會我們分析ProxyClassFactory()的apply方法
                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)
            //把value包裝成弱引用
            CacheValue<V> cacheValue = new CacheValue<>(value);

            // put into reverseMap
            // reverseMap是用來實現緩存的有效性
            reverseMap.put(cacheValue, Boolean.TRUE);

            // try replacing us with CacheValue (this should always succeed)
            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方法,代理類就是在這裡生成的。

首先看proxyClassCache的定義WeakCache<ClassLoader, Class<?>[], Class<?>>,泛型裡面第一個表示加載器K,第二個表示接口類P,第三個則是生成的代理類V。而V的生成則是通過ProxyClassFactory生成的。調用其apply();

//這裡的BiFunction<T, U, R>是個函數式接口,可以理解為用T,U兩種類型做參數,得到R類型的返回值
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
            //代理類訪問控制符: public ,final
            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.
             */
            //驗證所有非公共的接口在同一個包內;公共的就無需處理
            //生成包名和類名的邏輯,包名默認是com.sun.proxy,
            // 類名默認是$Proxy 加上一個自增的整數值
            //如果被代理類是 non-public proxy interface ,則用和被代理類接口一樣的包名
            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();
            //代理類的完全限定名,如com.sun.proxy.$Proxy0.calss
            String proxyName = proxyPkg + proxyClassNamePrefix + num;

            /*
             * Generate the specified proxy class.
             */
            //核心部分,生成代理類的字節碼
            byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
                proxyName, interfaces, accessFlags);
            try {
                //把代理類加載到JVM中,至此動態代理過程基本結束瞭
                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());
            }
        }
    }

然後調用getMethod(),將equals(),hashcode(),toString()等方法添加進去。然後遍歷所有接口的方法,添加到代理類中。最後將這些方法進行排序。

private static List<Method> getMethods(Class<?>[] interfaces) {
        List<Method> result = new ArrayList<Method>();
        try {
            result.add(Object.class.getMethod("equals", Object.class));
            result.add(Object.class.getMethod("hashCode", EmptyArray.CLASS));
            result.add(Object.class.getMethod("toString", EmptyArray.CLASS));
        } catch (NoSuchMethodException e) {
            throw new AssertionError();
        }

        getMethodsRecursive(interfaces, result);
        return result;
    }
private static void getMethodsRecursive(Class<?>[] interfaces, List<Method> methods) {
        for (Class<?> i : interfaces) {
            getMethodsRecursive(i.getInterfaces(), methods);
            Collections.addAll(methods, i.getDeclaredMethods());
        }
    }

最後輸出相關proxy class

package com.zhb.jdk.proxy;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Proxy;

import com.zhb.jdk.dynamicProxy.HelloworldImpl;

import sun.misc.ProxyGenerator;

/**
 * @author ZHB
 * @date 2018年8月31日下午11:35:07
 * @todo TODO
 */
public class DynamicProxyTest {

    public static void main(String[] args) {

        IUserService target = new UserServiceImpl();
        MyInvocationHandler handler = new MyInvocationHandler(target);
        //第一個參數是指定代理類的類加載器(我們傳入當前測試類的類加載器)
        //第二個參數是代理類需要實現的接口(我們傳入被代理類實現的接口,這樣生成的代理類和被代理類就實現瞭相同的接口)
        //第三個參數是invocation handler,用來處理方法的調用。這裡傳入我們自己實現的handler
        IUserService proxyObject = (IUserService) Proxy.newProxyInstance(DynamicProxyTest.class.getClassLoader(),
                target.getClass().getInterfaces(), handler);
        proxyObject.add("陳粒");

        String path = "D:/$Proxy0.class";
        byte[] classFile = ProxyGenerator.generateProxyClass("$Proxy0", HelloworldImpl.class.getInterfaces());
        FileOutputStream out = null;

        try {
            out = new FileOutputStream(path);
            out.write(classFile);
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
// Decompiled by Jad v1.5.8e2. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://kpdus.tripod.com/jad.html
// Decompiler options: packimports(3) fieldsfirst ansi space

import com.zhb.jdk.proxy.IUserService;
import java.lang.reflect.*;

public final class $Proxy0 extends Proxy
    implements IUserService
{

    private static Method m1;
    private static Method m2;
    private static Method m3;
    private static Method m0;
    //代理類的構造函數,其參數正是是InvocationHandler實例,
    //Proxy.newInstance方法就是通過通過這個構造函數來創建代理實例的
    public $Proxy0(InvocationHandler invocationhandler)
    {
        super(invocationhandler);
    }
     // Object類中的三個方法,equals,toString, hashCode
    public final boolean equals(Object obj)
    {
        try
        {
            return ((Boolean)super.h.invoke(this, m1, new Object[] {
                obj
            })).booleanValue();
        }
        catch (Error ) { }
        catch (Throwable throwable)
        {
            throw new UndeclaredThrowableException(throwable);
        }
    }

    public final String toString()
    {
        try
        {
            return (String)super.h.invoke(this, m2, null);
        }
        catch (Error ) { }
        catch (Throwable throwable)
        {
            throw new UndeclaredThrowableException(throwable);
        }
    }
    //接口代理方法
    public final void add(String s)
    {
        try
        {
            // invocation handler的 invoke方法在這裡被調用
            super.h.invoke(this, m3, new Object[] {
                s
            });
            return;
        }
        catch (Error ) { }
        catch (Throwable throwable)
        {
            throw new UndeclaredThrowableException(throwable);
        }
    }

    public final int hashCode()
    {
        try
        {
            // 在這裡調用瞭invoke方法。
            return ((Integer)super.h.invoke(this, m0, null)).intValue();
        }
        catch (Error ) { }
        catch (Throwable throwable)
        {
            throw new UndeclaredThrowableException(throwable);
        }
    }

    // 靜態代碼塊對變量進行一些初始化工作
    static 
    {
        try
        {
            m1 = Class.forName("java.lang.Object").getMethod("equals", new Class[] {
                Class.forName("java.lang.Object")
            });
            m2 = Class.forName("java.lang.Object").getMethod("toString", new Class[0]);
            m3 = Class.forName("com.zhb.jdk.proxy.IUserService").getMethod("add", new Class[] {
                Class.forName("java.lang.String")
            });
            m0 = Class.forName("java.lang.Object").getMethod("hashCode", new Class[0]);
        }
        catch (NoSuchMethodException nosuchmethodexception)
        {
            throw new NoSuchMethodError(nosuchmethodexception.getMessage());
        }
        catch (ClassNotFoundException classnotfoundexception)
        {
            throw new NoClassDefFoundError(classnotfoundexception.getMessage());
        }
    }
}

以上就是JDK動態代理步驟詳解(源碼分析)的詳細內容,更多關於JDK動態代理的資料請關註WalkonNet其它相關文章!

推薦閱讀: