動態代理invocationHandler詳解

以前對動態代理了解僅僅在於表層,一直以爲遙不可及,今天點開了 Proxy 類,欲知故事如何,需 Read The Source Code,再加上看一些別人的文章,對照着本身對源碼的理解,造成此文,通俗易懂,保你看後對動態代理又有了更加深刻的理解

先看一個例子熟悉一下吧
先定義接口,以後咱們再看,爲何JDK不能代理類,只能代理接口

public interface AddService {
    /**
     * <p>Test method</p>
     *
     * @param a number a
     * @param b number b
     * @return sum of a and b
     */
    int add(int a, int b);
}
實現類

public class AddServiceImpl implements AddService {

    @Override
    public int add(int a, int b) {
        return  a + b;
    }
}
Handler,繼承自InvocationHandler,該接口只有一個方法 invoke,你只須要實現它,而後利用反射 Object invoke = method.invoke(addService, args); 返回接口return invoke; 其餘的你想幹什麼都行,固然你也徹底改變這個這個實現,返回一些別的啥,壞事也是能夠的。getProxy方法裏面調用Proxy.newProxyInstance 獲取一個代理對象

public class AddServiceHandler implements InvocationHandler {
    private AddService addService;

    public AddServiceHandler(AddService addService) {
        this.addService = addService;
    }

    public AddService getProxy() {
        return (AddService) Proxy.newProxyInstance(addService.getClass().getClassLoader(),
                addService.getClass().getInterfaces(), this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("before");
        Object invoke = method.invoke(addService, args);
        System.out.println("after");
        return invoke;
    }
}
使用,首先獲取建立實例對象,而後構造一個Handler,再經過Handler獲取Proxy 對象,再調用接口的方法。咱們一切的疑問,可能就在 getProxy,他到底返回了什麼東西,可以讓咱們再調用接口方法的時候,執行的倒是 實現的Service 的方法,而且加了一些其它實現,聰明的你可能會說,這用靜態代理依然可以實現,而且要比動態代理來得簡單,爲何還要這樣複雜的實現。我如今能想到的是,靜態代理的話,你可能須要爲每個代理接口實現一個代理 Handler,然而 InvocationHandler 的話,你只須要爲相似的請求實現一個Handler,爲程序的擴展提供了大大的空間。

@Test
    public void dynamicProxyTest() {
        AddService service = new AddServiceImpl();
        AddServiceHandler addServiceHandler = new AddServiceHandler(service);
        AddService proxy = addServiceHandler.getProxy();
        Assert.assertEquals(3, proxy.add(1, 2));
    }
看到這裏,咱們有不少疑問
Proxy.newProxyInstance() 返回的是什麼東西
invoke 方法到底在哪調用
咱們在 target 裏面沒有看到其它任何附帶生成的 class,系統究竟是怎麼作的呢
那咱們就要好好看看這些方法的實現原理

Proxy.newProxyInstance

public class Proxy implements java.io.Serializable{}
private 的構造方法,裏面有一個 InvocationHandler,這個就是咱們傳入的 Handler,另外還有一個 proxyClassCache,一個代理類的緩存對象,我暫時不打算展開講這個東西,還沒搞明白,如今須要記住,這個存放這系統幫咱們生成的代理類,用了WeakReference 實現, GC 的時候會被回收。
裏面有兩個參數傳過去,KeyFactory() 先無論,ProxyClassFactory() 這個很重要,咱們以後遇到了再說

    /** parameter types of a proxy class constructor */
    private static final Class<?>[] constructorParams =
        { InvocationHandler.class };

    /**
     * a cache of proxy classes
     */
    private static final WeakCache<ClassLoader, Class<?>[], Class<?>>
        proxyClassCache = new WeakCache<>(new KeyFactory(), new ProxyClassFactory());

    /**
     * the invocation handler for this proxy instance.
     * @serial
     */
    protected InvocationHandler h;

    /**
     * Prohibits instantiation.
     */
    private Proxy() {
    }
爲了理解方便,我將一些無關精要的代碼剔除,留下最重要的兩個方法,getProxyClass0(loader, intfs) 根據loader和intfs 獲取代理類,經過這個方法咱們得到一個新的類字節碼,這個類是運行時生成的,經過這個代理類,getConstructor 獲取構造對象,調用newInstance建立一個實例對象,newInstance是能夠傳參的,只須要調用 constructor 的構造方法參數必須是 InvocationHandler.class,因此咱們傳的是 this 對象。

    public static Object newProxyInstance(ClassLoader loader,
                                          Class<?>[] interfaces,
                                          InvocationHandler h)
        throws IllegalArgumentException
    {
        /*
         * Look up or generate the designated proxy class.
         */
        Class<?> cl = getProxyClass0(loader, intfs);
        final Constructor<?> cons = cl.getConstructor(constructorParams);
        return cons.newInstance(new Object[]{h});
    }
65535 限制,這個get 比較高級,直接從緩存拿,剛開始看到可能以爲有點納悶,這個 proxyClassCache 以前遇到過了

    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);
    }
get方法首先建立一個 valuesMap,獲取subKey,裏面比較重要的就是subKeyFactory.apply(key, parameter),這個方法會幫咱們生成代理類的subKey,另外以後會創建一個Factory,當使用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);
                }
            }
        }
    }
ProxyClassFactory apply 不可不看,首先加載接口,而後使用ProxyGenerator.generateProxyClass 生成Class 字節碼文件,最後再調用 defineClass0 對其加載後返回關鍵字,做爲key,以後再根據這個key獲取到真正的class 對象,到這裏,Proxy類已經生成好,而且加載好了,直接返回,這個類是動態生成的,留在內存的數據

    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());
            }
        }
    }
那咱們能夠調用ProxyGenerator.generateProxyClass來看一次下這個生成的類,把它寫到文件裏,這個類大概就是這個樣子,就是咱們經過getProxy獲取到的實際類,以後就簡單了,能夠清楚的看到裏面熟悉的add方法,是經過調用了 invoke 來實現的

public final class $Proxy11 extends Proxy implements Service {
    private static Method m1;
    private static Method m2;
    private static Method m3;
    private static Method m0;

    public $Proxy11(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 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 add(int var1, int var2) throws  {
        try {
            return (Integer)super.h.invoke(this, m3, new Object[]{var1, var2});
        } catch (RuntimeException | Error var4) {
            throw var4;
        } catch (Throwable var5) {
            throw new UndeclaredThrowableException(var5);
        }
    }

    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"));
            m2 = Class.forName("java.lang.Object").getMethod("toString");
            m3 = Class.forName("proxy.Service").getMethod("add", Integer.TYPE, Integer.TYPE);
            m0 = Class.forName("java.lang.Object").getMethod("hashCode");
        } catch (NoSuchMethodException var2) {
            throw new NoSuchMethodError(var2.getMessage());
        } catch (ClassNotFoundException var3) {
            throw new NoClassDefFoundError(var3.getMessage());
        }
    }
}
至此,大部分邏輯已經搞清楚了,那咱們大概知道了爲何這個過程要比直接建立對象要慢,那是由於他第一次的時候須要動態的去建立字節碼,而後進行加載,初始化......雖然有緩存,可是因爲使用了 WeakReference,GC後有可能會被回收,那麼就得從新加載,必定程度上會下降效率,因此通常狀況下,咱們儘可能避免這種動態生成類的方式,而是用在編譯時生成類的方式取代,這即是 APT 技術的精髓。

做者:爲戰而生C
連接:https://www.jianshu.com/p/d0ee1ca57f14
來源:簡書
著做權歸做者全部。商業轉載請聯繫做者得到受權,非商業轉載請註明出處。
相關文章
相關標籤/搜索