動態代理原理及在 Android 中的應用

1、動態代理簡介

一、什麼是動態代理?

經過反射機制動態生成代理者對象的一種設計模式。java

二、如何區分靜態代理和動態代理?

  • 靜態代理:程序運行前,代理類已經存在。
  • 動態代理:程序運行前,代理類不存在,運行過程當中,動態生成代理類。

三、爲何要使用動態代理?

由於一個靜態代理類只能服務一種類型的目標對象,在目標對象較多的狀況下,會出現代理類較多、代碼量較大的問題。git

而使用動態代理動態生成代理者對象能避免這種狀況的發生。github

2、動態代理原理

先看一下動態代理的 UML 圖:面試

圖片參考:設計模式(11)動態代理 JDK VS CGLIB面試必問設計模式

一、經過數組

Proxy.newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h); 
複製代碼

反射生成代理類對象。緩存

二、調用動態代理類對象方法,會回調app

h.invoke(thisObject proxy, Method method, Object[] args); //最終調用的是 InvocationHandler 實現類中重寫的 invoke() 方法
複製代碼

三、最終,經過ide

method.invoke(Object obj, Object... args);
複製代碼

調用目標對象的方法。函數

3、動態代理實戰

一、使用步驟

(1)聲明目標對象的抽象接口。

(2)聲明調用處理類(實現 InvocationHandler 接口)。

(3)生成目標對象類(實現目標對象的抽象接口,這裏因爲每一個代理類都繼承了 Proxy 類,又 Java 的單繼承特性,因此,只能針對接口建立代理類,不能針對類建立代理類,後續會解釋)。

(4)生成代理類對象。

(5)經過代理類對象,調用目標對象的方法。

二、實戰代碼

// (1)聲明目標對象的抽象接口
public interface ISubject {
    void buy();
}

// (2)聲明調用處理類(實現 InvocationHandler 接口)
public class InvocationHandlerImpl implements InvocationHandler{
    private Object mRealObject;

    public InvocationHandlerImpl(Object realObject) {
        mRealObject = realObject;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("proxy invoke, proxy = " + proxy.getClass() + ", realObject = " + mRealObject.getClass());
        Object result = method.invoke(mRealObject, args);
        return result;
    }
}

// (3.1)實現目標對象類 1
public class Buyer1 implements ISubject {
    @Override
    public void buy() {
        System.out.println("buyer1 buy");
    }
}

// (3.2)實現目標對象類 2
public class Buyer2 implements ISubject {
    @Override
    public void buy() {
        System.out.println("buyer2 buy");
    }
}

public class DynamicProxyDemo {
    public static void main(String[] args) {
        // 在工程目錄下生成 $Proxy0 的 class 文件
        System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");

        Buyer1 buyer1 = new Buyer1(); //建立目標對象的對象
        InvocationHandlerImpl invocationHandlerImpl1 = new InvocationHandlerImpl(buyer1); //建立調用處理類對象
        
        //(4)生成代理類對象
        ISubject buyer1Proxy = (ISubject) Proxy.newProxyInstance(buyer1.getClass().getClassLoader(), buyer1.getClass().getInterfaces(), invocationHandlerImpl1);
        
        //(5)經過代理類對象,調用目標對象的方法
        buyer1Proxy.buy();

        System.out.println("目標對象1:" + buyer1.getClass());
        System.out.println("代理對象1:" + buyer1Proxy.getClass());

        Buyer2 buyer2 = new Buyer2();
        InvocationHandlerImpl invocationHandlerImpl2 = new InvocationHandlerImpl(buyer2);
        ISubject buyer2Proxy = (ISubject) Proxy.newProxyInstance(buyer2.getClass().getClassLoader(), buyer2.getClass().getInterfaces(), invocationHandlerImpl2);
        buyer2Proxy.buy();

        System.out.println("目標對象2:" + buyer2.getClass());
        System.out.println("代理對象2:" + buyer2Proxy.getClass());
    }
}

複製代碼

咱們運行一下這個 Demo,運行結果以下:

proxy invoke, proxy = class com.sun.proxy.$Proxy0, realObject = class com.trampcr.proxy.Buyer1
buyer1 buy
目標對象1:class com.trampcr.proxy.Buyer1
代理對象1:class com.sun.proxy.$Proxy0
proxy invoke, proxy = class com.sun.proxy.$Proxy0, realObject = class com.trampcr.proxy.Buyer2
buyer2 buy
目標對象2:class com.trampcr.proxy.Buyer2
代理對象2:class com.sun.proxy.$Proxy0
複製代碼

從日誌中能夠看到代理類是 com.sun.proxy.$Proxy0,咱們都知道動態代理是動態生成代理類對象,若是能看到動態生成的這個代理類,是否是能更好的理解動態代理的原理?

細心的同窗可能已經看到以上代碼中有一行比較特殊的代碼,這行代碼的做用是把 sun.misc.ProxyGenerator.saveGeneratedFiles 這個變量賦值爲 true,這個變量爲 true 時,將會在工程目錄下生成 $Proxy0 的 class 文件(因爲生成代理類的 ProxyGenerator 類在 sun.misc 包中,在 Android Studio 中沒法調用,因此這裏是在 Intellij 中寫的 Demo 進行調用):

System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");
複製代碼

運行後,在項目的 src 同級目錄下,會出現一個 com.sun.proxy 包,這個包裏放的就是動態生成的代理類 $Proxy0。

package com.sun.proxy;

// $Proxy0 默認繼承了 Proxy,因此這裏解釋了「只能針對接口(ISubject)建立代理類,不能針對類建立代理類」。
public final class $Proxy0 extends Proxy implements ISubject {
    private static Method m1;
    private static Method m2;
    private static Method m3;
    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})).booleanValue();
        } 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 void buy() throws {
        try {
            // m3 = Class.forName("com.trampcr.proxy.ISubject").getMethod("buy", new Class[0]);
            // 經過代理類訪問目標對象的方法
            // 最終會經過 super.h.invoke() 回調到咱們重寫的 InvocationHandler 實現類的 invoke() 中。
            super.h.invoke(this, m3, (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)).intValue();
        } catch (RuntimeException | Error var2) {
            throw var2;
        } catch (Throwable var3) {
            throw new UndeclaredThrowableException(var3);
        }
    }

    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.trampcr.proxy.ISubject").getMethod("buy", new Class[0]);
            m0 = Class.forName("java.lang.Object").getMethod("hashCode", new Class[0]);
        } catch (NoSuchMethodException var2) {
            throw new NoSuchMethodError(var2.getMessage());
        } catch (ClassNotFoundException var3) {
            throw new NoClassDefFoundError(var3.getMessage());
        }
    }
}

複製代碼

看到這裏咱們對動態代理的使用以及動態生成的代理類有了必定認識,但對於代理對象是如何動態生成的,還須要進一步看源碼。

4、動態代理源碼分析

生成動態代理對象主要是經過:Proxy.newProxyInstance()。

這裏的源碼分析分爲兩個版本:JDK 1.7,JDK 1.8。

JDK 1.7

// loader:生成代理對象的類加載器(須要和目標對象是同一個類加載器)
// interfaces:目標對象實現的接口,代理類也須要實現這個接口
// h:InvocationHandler 的實現類對象,動態代理對象調用目標對象方法時,最終會回調 h.invoke()
public static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h) throws IllegalArgumentException {
        
    ... //省略部分邏輯,直接看主要邏輯
    
    // 一、經過 loader 和 interfaces 建立動態代理類
    Class<?> cl = getProxyClass0(loader, interfaces);

    try {
        // 二、經過反射機制獲取動態代理類的構造函數(參數類型是 InvocationHandler.class 類型)
        final Constructor<?> cons = cl.getConstructor(constructorParams);
        final InvocationHandler ih = h;
        
        ...
        
            // 三、經過動態代理類的構造函數和調用處理器對象建立代理類實例
            return newInstance(cons, ih);
        ...
        
    } catch (NoSuchMethodException e) {
        throw new InternalError(e.toString());
    }
}

// loader:生成代理對象的類加載器
// interfaces:目標對象實現的接口,如下簡稱接口
private static Class<?> getProxyClass0(ClassLoader loader, Class<?>... interfaces) {
    
    ...

    Class<?> proxyClass = null;

    // 接口名稱數組,用於收集接口的名稱做爲代理類緩存的 key
    String[] interfaceNames = new String[interfaces.length];

    // 接口集合,用於檢查是否重複的接口
    Set<Class<?>> interfaceSet = new HashSet<>();

    // 遍歷目標對象實現的接口
    for (int i = 0; i < interfaces.length; i++) {
        // 獲取接口名稱
        String interfaceName = interfaces[i].getName();
        Class<?> interfaceClass = null;
        try {
            // 經過反射加載目標類實現的接口到內存中
            interfaceClass = Class.forName(interfaceName, false, loader);
        } catch (ClassNotFoundException e) {
        }
        if (interfaceClass != interfaces[i]) {
            throw new IllegalArgumentException(
                interfaces[i] + " is not visible from class loader");
        }

        ...

        // 若是接口重複,拋出異常
        if (interfaceSet.contains(interfaceClass)) {
            throw new IllegalArgumentException("repeated interface: " + interfaceClass.getName());
        }
        interfaceSet.add(interfaceClass);
        interfaceNames[i] = interfaceName;
    }

    // 將接口名稱數組轉換爲接口名稱列表
    List<String> key = Arrays.asList(interfaceNames);

    // 經過 Classloader 獲取或者建立一個代理類緩存
    Map<List<String>, Object> cache;
    
    // 將一個 ClassLoader 映射到該 ClassLoader 的代理類緩存
    // private static Map<ClassLoader, Map<List<String>, Object>> loaderToCache = new WeakHashMap<>();
    
    synchronized (loaderToCache) {
        cache = loaderToCache.get(loader);
        if (cache == null) {
            cache = new HashMap<>();
            loaderToCache.put(loader, cache);
        }
    }

    synchronized (cache) {
        do {
            Object value = cache.get(key);
            if (value instanceof Reference) {
                proxyClass = (Class<?>) ((Reference) value).get();
            }
            if (proxyClass != null) {
                return proxyClass;
            } else if (value == pendingGenerationMarker) {
                // 正在建立代理類,等待,代理類建立完成後會執行 notifyAll() 進行通知
                try {
                    cache.wait();
                } catch (InterruptedException e) {
                }
                continue;
            } else {
                // 代理類爲空,往代理類緩存中添加一個 pendingGenerationMarker 標識,表示正在建立代理類
                cache.put(key, pendingGenerationMarker);
                break;
            }
        } while (true); //這是一個死循環,直到代理類不爲空時,返回代理類
    }

    // 如下爲生成代理類邏輯
    try {
        String proxyPkg = null;

        // 遍歷接口的訪問修飾符,若是是非 public 的,代理類包名爲接口的包名
        for (int i = 0; i < interfaces.length; i++) {
            int flags = interfaces[i].getModifiers();
            if (!Modifier.isPublic(flags)) {
                String name = interfaces[i].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) {
            // 若是接口都是 public 的,則用 com.sun.proxy 做爲包名,這個從 $Proxy0 類中能夠看到
            proxyPkg = ReflectUtil.PROXY_PACKAGE + ".";
        }

        {
            long num;
            synchronized (nextUniqueNumberLock) {
                num = nextUniqueNumber++;
            }
            String proxyName = proxyPkg + proxyClassNamePrefix + num;

            // 根據代理類全路徑和接口建立代理類的字節碼
            byte[] proxyClassFile = ProxyGenerator.generateProxyClass(proxyName, interfaces);
            try {
                // 根據代理類的字節碼生成代理類
                proxyClass = defineClass0(loader, proxyName, proxyClassFile, 0, proxyClassFile.length);
            } catch (ClassFormatError e) {
                throw new IllegalArgumentException(e.toString());
            }
        }
        
        // 建立的全部代理類集合
        // private static Map<Class<?>, Void> proxyClasses = Collections.synchronizedMap(new WeakHashMap<Class<?>, Void>());
        proxyClasses.put(proxyClass, null);
    } finally {
        synchronized (cache) {
            if (proxyClass != null) {
                // 建立好代理類後存到代理類緩存中
                cache.put(key, new WeakReference<Class<?>>(proxyClass));
            } else {
                // 不然,清除以前存入的 pendingGenerationMarker 標識
                cache.remove(key);
            }
            cache.notifyAll();
        }
    }
    return proxyClass;
}
複製代碼

源碼有點多,總結一下動態生成代理類對象的過程:

一、經過 loader 和 interfaces 建立動態代理類(首先,根據代理類全路徑和接口建立代理類的字節碼,其次,根據代理類的字節碼生成代理類)。

二、經過反射機制獲取動態代理類的構造函數(參數類型是 InvocationHandler.class 類型)。

三、經過動態代理類的構造函數和調用處理器對象建立代理類實例。

最後,動態建立的代理類能夠看上邊貼過的代碼:$Proxy0。

JDK 1.8

// loader:生成代理對象的類加載器(須要和目標對象是同一個類加載器)
// interfaces:目標對象實現的接口,代理類也須要實現這個接口
// h:InvocationHandler 的實現類對象,動態代理對象調用目標對象方法時,最終會回調 h.invoke()
public static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h) throws IllegalArgumentException {
    ..

    // clone 傳入的目標對象實現的接口
    final Class<?>[] intfs = interfaces.clone();
        
    ...

     1、經過 loader 和 interfaces 建立動態代理類
    Class<?> cl = getProxyClass0(loader, intfs);

    try {
        ...

        // 二、經過反射機制獲取動態代理類的構造函數(參數類型是 InvocationHandler.class 類型)
        final Constructor<?> cons = cl.getConstructor(constructorParams);
            
        ...
            
        // 三、經過動態代理類的構造函數和調用處理器對象建立代理類實例
        return cons.newInstance(new Object[]{h});
    } 
        
    ...
}

private static Class<?> getProxyClass0(ClassLoader loader, Class<?>... interfaces) {
    
    ...

    // 代理類緩存
    // private static final WeakCache<ClassLoader, Class<?>[], Class<?>> proxyClassCache = 
    // new WeakCache<>(new KeyFactory(), new ProxyClassFactory());
    
    // 根據傳入的 loader 和 interfaces 從緩存中獲取代理類,若是沒有緩存,經過 ProxyClassFactory 建立代理類
    return proxyClassCache.get(loader, interfaces);
}

public V get(K key, P parameter) {
        
    ...

    // private final ReferenceQueue<K> refQueue = new ReferenceQueue<>();
    Object cacheKey = CacheKey.valueOf(key, refQueue); //把 key 轉爲 CacheKey

    // map 的 key 是 Object 類型,key 的值支持 null
    // private final ConcurrentMap<Object, ConcurrentMap<Object, Supplier<V>>> map = new ConcurrentHashMap<>();
    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;
        }
    }

    // 關鍵點一、subKeyFactory 被傳進來的是 new KeyFactory(),稍後看下 KeyFactory.apply()
    Object subKey = Objects.requireNonNull(subKeyFactory.apply(key, parameter));
    Supplier<V> supplier = valuesMap.get(subKey);
    Factory factory = null;

    // 這是一個死循環,循環跳出條件是 value 不爲空
    // 關鍵點二、這裏比較關鍵的點是 supplier.get(),這裏會經過 ProxyClassFactory 建立代理類
    while (true) {
        if (supplier != null) {
            // supplier 多是一個 Factory 或 CacheValue<V> 實例
            V value = supplier.get();
            if (value != null) {
                return value;
            }
        }

        if (factory == null) {
            factory = new Factory(key, parameter, subKey, valuesMap);
        }

        if (supplier == null) {
            supplier = valuesMap.putIfAbsent(subKey, factory);
            if (supplier == null) {
                supplier = factory;
            }
        } else {
            if (valuesMap.replace(subKey, supplier, factory)) {
                supplier = factory;
            } else {
                supplier = valuesMap.get(subKey);
            }
        }
    }
}

// 關鍵點一、獲取 subKey(KeyFactory.apply())
// 這個方法主要是根據接口個數建立 subKey
public Object apply(ClassLoader classLoader, Class<?>[] interfaces) {
    switch (interfaces.length) {
        case 1: return new Key1(interfaces[0]);
        case 2: return new Key2(interfaces[0], interfaces[1]);
        
        // private static final Object key0 = new Object();
        case 0: return key0;
        default: return new KeyX(interfaces);
    }
}

// 關鍵點二、supplier.get() == WeakCache.Factory.get()
public synchronized V get() {
            // 雙重校驗
            Supplier<V> supplier = valuesMap.get(subKey);
            if (supplier != this) {
                // 出現這種狀況的緣由可能有:
                // 一、被 CacheValue 代替
                // 二、由於失敗被移除
                return null;
            }

            V value = null;
            try {
                // 關鍵點三、valueFactory = ProxyClassFactory
                // 真正建立代理類的代碼在 ProxyClassFactory.apply() 中
                value = Objects.requireNonNull(valueFactory.apply(key, parameter));
            } finally {
                if (value == null) {
                    valuesMap.remove(subKey, this);
                }
            }

            assert value != null;

            CacheValue<V> cacheValue = new CacheValue<>(value);

            if (valuesMap.replace(subKey, this, cacheValue)) {
                reverseMap.put(cacheValue, Boolean.TRUE);
            } else {
                throw new AssertionError("Should not reach here");
            }

            return value;
        }

// 關鍵點三、Proxy.ProxyClassFactory.apply():建立代理類
// 這個方法的代碼就很熟悉了,和 JDK 1.7 中 getProxyClass0() 方法幾乎同樣
public Class<?> apply(ClassLoader loader, Class<?>[] interfaces) {
    Map<Class<?>, Boolean> interfaceSet = new IdentityHashMap<>(interfaces.length);
    for (Class<?> intf : interfaces) {
        Class<?> interfaceClass = null;
        try {
            interfaceClass = Class.forName(intf.getName(), false, loader);
        } catch (ClassNotFoundException e) {
        }
        
        ...
    }

    String proxyPkg = null;
    int accessFlags = Modifier.PUBLIC | Modifier.FINAL;

    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) {
        proxyPkg = ReflectUtil.PROXY_PACKAGE + ".";
    }

    long num = nextUniqueNumber.getAndIncrement();
    String proxyName = proxyPkg + proxyClassNamePrefix + num;

    byte[] proxyClassFile = ProxyGenerator.generateProxyClass(proxyName, interfaces, accessFlags);
    try {
        return defineClass0(loader, proxyName, proxyClassFile, 0, proxyClassFile.length);
    } catch (ClassFormatError e) {
        throw new IllegalArgumentException(e.toString());
    }
}

複製代碼

JDK 1.7 和 JDK 1.8 中的源碼分析完了,咱們發現其實生成代理類的方法都是同樣的,區別主要體如今緩存方式上,JDK 1.8 做了性能上的優化,速度明顯比 1.7 提高了不少。

5、動態代理在 Android 中的應用

一、Android 的跨進程通訊中使用了動態代理

好比 Activity 的啓動過程,其實就隱藏了遠程代理的使用。

二、Retrofit 中 create() 方法經過動態代理獲取接口對象。

這些場景可能不夠全面,你們能夠在評論區補充,看到新的場景,我後續也會補充的。

參考:

公共技術點之 Java 動態代理

代理模式(Proxy Pattern):動態代理 - 最易懂的設計模式解析

相關文章
相關標籤/搜索