詳述 JDK 和 CGLIB 動態代理的實現原理以及兩者的區別

版權聲明:本文的內容大都來自於「街燈下的小草」的博文,略作修改。

代理

代理,我們一般又稱之爲“代理模式”,是一種常見設計模式,其含義是:爲其他對象提供一種代理以控制對這個對象的訪問。在某些情況下,一個對象不適合或者不能直接引用另一個對象,而代理對象可以在客戶端和目標對象之間起到中介的作用。

代理分爲靜態代理和動態代理兩類,兩者的主要區別就是代理類生成的時機,其中:

  • 靜態代理:在程序運行前,創建代理類,實現代理邏輯;
  • 動態代理:在程序運行時,運用反射機制動態創建代理類。

特別地,動態代理又有兩種主要的實現方式,分別爲:JDK 動態代理和 CGLIB 動態代理。

在本文中,我們就來講解動態代理的兩種實現方式、原理以及區別。

JDK 動態代理

顧名思義,JDK 動態代理就是基於 JDK 實現的代理模式,主要運用了其攔截器和反射機制,其代理對象是由 JDK 動態生成的,而不像靜態代理方式寫死代理對象和被代理類。JDK 代理是不需要第三方庫支持的,只需要 JDK 環境就可以進行代理,使用條件:

  • 必須實現InvocationHandler接口;
  • 使用Proxy.newProxyInstance產生代理對象;
  • 被代理的對象必須要實現接口。

代碼示例

使用 JDK 動態代理的五大步驟:

  1. 通過實現InvocationHandler接口來自定義自己的InvocationHandler
  2. 通過Proxy.getProxyClass獲得動態代理類;
  3. 通過反射機制獲得代理類的構造方法,方法簽名爲getConstructor(InvocationHandler.class)
  4. 通過構造函數獲得代理對象並將自定義的InvocationHandler實例對象傳爲參數傳入;
  5. 通過代理對象調用目標方法。

接下來,我們就按上面的 5 個步驟,寫一個 JDK 動態代理的示例。

  • IHello,自定義接口
public interface IHello {
    void sayHello();
}
  • HelloImpl,接口實現類
public class HelloImpl implements IHello {
    @Override
    public void sayHello() {
        System.out.println("Hello world!");
    }
}
  • MyInvocationHandler,實現InvocationHandler接口
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
 
public class MyInvocationHandler implements InvocationHandler {
 
    /** 目標對象 */
    private Object target;
 
    public MyInvocationHandler(Object target){
        this.target = target;
    }
 
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("------插入前置通知代碼-------------");
        // 執行相應的目標方法
        Object rs = method.invoke(target,args);
        System.out.println("------插入後置處理代碼-------------");
        return rs;
    }
}
  • MyProxyTest,測試類
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Proxy;
 
/**
 * 使用JDK動態代理的五大步驟:
 * 1.通過實現InvocationHandler接口來自定義自己的InvocationHandler;
 * 2.通過Proxy.getProxyClass獲得動態代理類
 * 3.通過反射機制獲得代理類的構造方法,方法簽名爲getConstructor(InvocationHandler.class)
 * 4.通過構造函數獲得代理對象並將自定義的InvocationHandler實例對象傳爲參數傳入
 * 5.通過代理對象調用目標方法
 */
public class MyProxyTest {
    public static void main(String[] args)
            throws NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException {
        // =========================第一種==========================
        // 1、生成$Proxy0的class文件
        System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");
        // 2、獲取動態代理類
        Class proxyClazz = Proxy.getProxyClass(IHello.class.getClassLoader(),IHello.class);
        // 3、獲得代理類的構造函數,並傳入參數類型InvocationHandler.class
        Constructor constructor = proxyClazz.getConstructor(InvocationHandler.class);
        // 4、通過構造函數來創建動態代理對象,將自定義的InvocationHandler實例傳入
        IHello iHello1 = (IHello) constructor.newInstance(new MyInvocationHandler(new HelloImpl()));
        // 5、通過代理對象調用目標方法
        iHello1.sayHello();
 
        // ==========================第二種=============================
        /**
         * Proxy類中還有個將2~4步驟封裝好的簡便方法來創建動態代理對象,
         *其方法簽名爲:newProxyInstance(ClassLoader loader,Class<?>[] instance, InvocationHandler h)
         */
        IHello  iHello2 = (IHello) Proxy.newProxyInstance(IHello.class.getClassLoader(), // 加載接口的類加載器
                new Class[]{IHello.class}, // 一組接口
                new MyInvocationHandler(new HelloImpl())); // 自定義的InvocationHandler
        iHello2.sayHello();
    }
}

運行上述測試類,其結果如下圖所示:
jdk-proxy-test

源碼分析

Proxy.newProxyInstance()方法爲切入點來剖析代理類的生成及代理方法的調用。

@CallerSensitive
public static Object newProxyInstance(ClassLoader loader,
                                          Class<?>[] interfaces,
                                          InvocationHandler h) throws IllegalArgumentException {
	    // 如果h爲空直接拋出空指針異常,之後所有的單純的判斷null並拋異常,都是此方法
        Objects.requireNonNull(h);
	    // 拷貝類實現的所有接口
        final Class<?>[] intfs = interfaces.clone();
	    // 獲取當前系統安全接口
        final SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
	        // Reflection.getCallerClass返回調用該方法的方法的調用類;loader:接口的類加載器
	        // 進行包訪問權限、類加載器權限等檢查
            checkProxyAccess(Reflection.getCallerClass(), loader, intfs);
        }
 
        // 查找或生成指定的代理類
        Class<?> cl = getProxyClass0(loader, intfs);
 
        // 用指定的調用處理程序調用它的構造函數
        try {
            if (sm != null) {
                checkNewProxyPermission(Reflection.getCallerClass(), cl);
            }
            
		   /*
		    * 獲取代理類的構造函數對象。
		    * constructorParams是類常量,作爲代理類構造函數的參數類型,常量定義如下:
		    * 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;
                    }
                });
            }
	        // 根據代理類的構造函數對象來創建需要返回的代理類對象
            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);
        }
}

如上述代碼所示,newProxyInstance()方法幫我們執行了生成代理類、獲取構造器和生成代理對象這三步:

  • 生成代理類:Class<?> cl = getProxyClass0(loader, intfs);
  • 獲取構造器:final Constructor<?> cons = cl.getConstructor(constructorParams);
  • 生成代理對象:cons.newInstance(new Object[]{h});

那麼,Proxy.getProxyClass0()又是如何生成代理類的呢?

private static Class<?> getProxyClass0(ClassLoader loader,
                                           Class<?>... interfaces) {
		// 接口數不得超過65535個,這麼大,足夠使用的了
        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);
}

如果緩存中沒有代理類,Proxy中的ProxyClassFactory如何創建代理類?從get()方法追蹤進去看看。

public V get(K key, P parameter) {// key:類加載器;parameter:接口數組
        // 檢查指定類型的對象引用不爲空null。當參數爲null時,拋出空指針異常。
        Objects.requireNonNull(parameter);
		// 清除已經被GC回收的弱引用
        expungeStaleEntries();
		// 將ClassLoader包裝成CacheKey, 作爲一級緩存的key
        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
		// 根據代理類實現的接口數組來生成二級緩存key
        Object subKey = Objects.requireNonNull(subKeyFactory.apply(key, parameter));
		// 通過subKey獲取二級緩存值
        Supplier<V> supplier = valuesMap.get(subKey);
        Factory factory = null;
		// 這個循環提供了輪詢機制, 如果條件爲假就繼續重試直到條件爲真爲止
        while (true) {
            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
					// 到這裏表明成功將factory放入緩存
                    supplier = factory;
                }
				// 否則, 可能期間有其他線程修改了值, 那麼就不再繼續給subKey賦值, 而是取出來直接用
                // else retry with winning supplier
            } else {
			    // 期間可能其他線程修改了值, 那麼就將原先的值替換
                if (valuesMap.replace(subKey, supplier, factory)) {
                    // successfully replaced
                    // cleared CacheEntry / unsuccessful Factory
                    // with our Factory
					// 成功將factory替換成新的值
                    supplier = factory;
                } else {
                    // retry with current supplier
					// 替換失敗, 繼續使用原先的值
                    supplier = valuesMap.get(subKey);
                }
            }
        }
}

get方法中,先調用Objects.requireNonNull(subKeyFactory.apply(key, parameter))獲取subKey,其中subKeyFactory又調用了apply方法,具體實現在ProxyClassFactory中完成。ProxyClassFactory.apply()實現代理類的創建。

private static final class ProxyClassFactory implements BiFunction<ClassLoader, Class<?>[], Class<?>> {
		// 統一代理類的前綴名都以$Proxy
        private static final String proxyClassNamePrefix = "$Proxy";
 
        // 使用唯一的編號給作爲代理類名的一部分,如$Proxy0,$Proxy1等
        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) {
                // 驗證指定的類加載器(loader)加載接口所得到的Class對象(interfaceClass)是否與intf對象相同
                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");
                }
                // 驗證該Class對象是不是接口
                if (!interfaceClass.isInterface()) {
                    throw new IllegalArgumentException(
                        interfaceClass.getName() + " is not an interface");
                }
                // 驗證該接口是否重複
                if (interfaceSet.put(interfaceClass, Boolean.TRUE) != null) {
                    throw new IllegalArgumentException(
                        "repeated interface: " + interfaceClass.getName());
                }
            }
	   		 // 聲明代理類所在包
            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) {
                // if no non-public proxy interfaces, use com.sun.proxy package
		/*如果都是public接口,那麼生成的代理類就在com.sun.proxy包下如果報java.io.FileNotFoundException: com\sun\proxy\$Proxy0.class 
		(系統找不到指定的路徑。)的錯誤,就先在你項目中創建com.sun.proxy路徑*/
                proxyPkg = ReflectUtil.PROXY_PACKAGE + ".";
            }
 
            /*
             * Choose a name for the proxy class to generate.
	    	 * nextUniqueNumber 是一個原子類,確保多線程安全,防止類名重複,類似於:$Proxy0,$Proxy1......
             */
            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 {
                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()方法中,方法簽名如下:

  • byte[] proxyClassFile = ProxyGenerator.generateProxyClass(proxyName, interfaces, accessFlags);
public static byte[] generateProxyClass(final String name, Class<?>[] interfaces, int accessFlags) {
        ProxyGenerator gen = new ProxyGenerator(name, interfaces, accessFlags);
        // 真正生成字節碼的方法
        final byte[] classFile = gen.generateClassFile();
        // 如果saveGeneratedFiles爲true 則生成字節碼文件,所以在開始我們要設置這個參數
        // 當然,也可以通過返回的bytes自己輸出
        if (saveGeneratedFiles) {
            java.security.AccessController.doPrivileged( new java.security.PrivilegedAction<Void>() {
                        public Void run() {
                            try {
                                int i = name.lastIndexOf('.');
                                Path path;
                                if (i > 0) {
                                    Path dir = Paths.get(name.substring(0, i).replace('.', File.separatorChar));
                                    Files.createDirectories(dir);
                                    path = dir.resolve(name.substring(i+1, name.length()) + ".class");
                                } else {
                                    path = Paths.get(name + ".class");
                                }
                                Files.write(path, classFile);
                                return null;
                            } catch (IOException e) {
                                throw new InternalError( "I/O exception saving generated file: " + e);
                            }
                        }
                    });
        }
        return classFile;
}

代理類生成的最終方法是ProxyGenerator.generateClassFile()

private byte[] generateClassFile() {
        /* ============================================================
         * Step 1: Assemble ProxyMethod objects for all methods to generate proxy dispatching code for.
         * 步驟1:爲所有方法生成代理調度代碼,將代理方法對象集合起來。
         */
        //增加 hashcode、equals、toString方法
        addProxyMethod(hashCodeMethod, Object.class);
        addProxyMethod(equalsMethod, Object.class);
        addProxyMethod(toStringMethod, Object.class);
        // 獲得所有接口中的所有方法,並將方法添加到代理方法中
        for (Class<?> intf : interfaces) {
            for (Method m : intf.getMethods()) {
                addProxyMethod(m, intf);
            }
        }
 
        /*
         * 驗證方法簽名相同的一組方法,返回值類型是否相同;意思就是重寫方法要方法簽名和返回值一樣
         */
        for (List<ProxyMethod> sigmethods : proxyMethods.values()) {
            checkReturnTypes(sigmethods);
        }
 
        /* ============================================================
         * Step 2: Assemble FieldInfo and MethodInfo structs for all of fields and methods in the class we are generating.
         * 爲類中的方法生成字段信息和方法信息
         */
        try {
            // 生成代理類的構造函數
            methods.add(generateConstructor());
            for (List<ProxyMethod> sigmethods : proxyMethods.values()) {
                for (ProxyMethod pm : sigmethods) {
                    // add static field for method's Method object
                    fields.add(new FieldInfo(pm.methodFieldName,
                            "Ljava/lang/reflect/Method;",
                            ACC_PRIVATE | ACC_STATIC));
                    // generate code for proxy method and add it
					// 生成代理類的代理方法
                    methods.add(pm.generateMethod());
                }
            }
            // 爲代理類生成靜態代碼塊,對一些字段進行初始化
            methods.add(generateStaticInitializer());
        } catch (IOException e) {
            throw new InternalError("unexpected I/O Exception", e);
        }
 
        if (methods.size() > 65535) {
            throw new IllegalArgumentException("method limit exceeded");
        }
        if (fields.size() > 65535) {
            throw new IllegalArgumentException("field limit exceeded");
        }
 
        /* ============================================================
         * Step 3: Write the final class file.
         * 步驟3:編寫最終類文件
         */
        /*
         * Make sure that constant pool indexes are reserved for the following items before starting to write the final class file.
         * 在開始編寫最終類文件之前,確保爲下面的項目保留常量池索引。
         */
        cp.getClass(dotToSlash(className));
        cp.getClass(superclassName);
        for (Class<?> intf: interfaces) {
            cp.getClass(dotToSlash(intf.getName()));
        }
 
        /*
         * Disallow new constant pool additions beyond this point, since we are about to write the final constant pool table.
         * 設置只讀,在這之前不允許在常量池中增加信息,因爲要寫常量池表
         */
        cp.setReadOnly();
 
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        DataOutputStream dout = new DataOutputStream(bout);
 
        try {
            // u4 magic;
            dout.writeInt(0xCAFEBABE);
            // u2 次要版本;
            dout.writeShort(CLASSFILE_MINOR_VERSION);
            // u2 主版本
            dout.writeShort(CLASSFILE_MAJOR_VERSION);
 
            cp.write(dout);             // (write constant pool)
 
            // u2 訪問標識;
            dout.writeShort(accessFlags);
            // u2 本類名;
            dout.writeShort(cp.getClass(dotToSlash(className)));
            // u2 父類名;
            dout.writeShort(cp.getClass(superclassName));
            // u2 接口;
            dout.writeShort(interfaces.length);
            // u2 interfaces[interfaces_count];
            for (Class<?> intf : interfaces) {
                dout.writeShort(cp.getClass(
                        dotToSlash(intf.getName())));
            }
            // u2 字段;
            dout.writeShort(fields.size());
            // field_info fields[fields_count];
            for (FieldInfo f : fields) {
                f.write(dout);
            }
            // u2 方法;
            dout.writeShort(methods.size());
            // method_info methods[methods_count];
            for (MethodInfo m : methods) {
                m.write(dout);
            }
            // u2 類文件屬性:對於代理類來說沒有類文件屬性;
            dout.writeShort(0); // (no ClassFile attributes for proxy classes)
 
        } catch (IOException e) {
            throw new InternalError("unexpected I/O Exception", e);
        }
 
        return bout.toByteArray();
}

通過addProxyMethod()添加hashcodeequalstoString方法。

private void addProxyMethod(Method var1, Class var2) {
        String var3 = var1.getName();  //方法名
        Class[] var4 = var1.getParameterTypes();   //方法參數類型數組
        Class var5 = var1.getReturnType();    //返回值類型
        Class[] var6 = var1.getExceptionTypes();   //異常類型
        String var7 = var3 + getParameterDescriptors(var4);   //方法簽名
        Object var8 = (List)this.proxyMethods.get(var7);   //根據方法簽名卻獲得proxyMethods的Value
        if(var8 != null) {    //處理多個代理接口中重複的方法的情況
            Iterator var9 = ((List)var8).iterator();
            while(var9.hasNext()) {
                ProxyGenerator.ProxyMethod var10 = (ProxyGenerator.ProxyMethod)var9.next();
                if(var5 == var10.returnType) {
                    /*歸約異常類型以至於讓重寫的方法拋出合適的異常類型,我認爲這裏可能是多個接口中有相同的方法,而這些相同的方法拋出的異常類                      型又不同,所以對這些相同方法拋出的異常進行了歸約*/
                    ArrayList var11 = new ArrayList();
                    collectCompatibleTypes(var6, var10.exceptionTypes, var11);
                    collectCompatibleTypes(var10.exceptionTypes, var6, var11);
                    var10.exceptionTypes = new Class[var11.size()];
                    //將ArrayList轉換爲Class對象數組
                    var10.exceptionTypes = (Class[])var11.toArray(var10.exceptionTypes);
                    return;
                }
            }
        } else {
            var8 = new ArrayList(3);
            this.proxyMethods.put(var7, var8);
        }    
        ((List)var8).add(new ProxyGenerator.ProxyMethod(var3, var4, var5, var6, var2, null));
       /*如果var8爲空,就創建一個數組,並以方法簽名爲key,proxymethod對象數組爲value添加到proxyMethods*/
}

生成的代理對象$Proxy0.class字節碼反編譯:

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 IHello // 繼承了Proxy類和實現IHello接口
{
  // 變量,都是private static Method  XXX
  private static Method m1;
  private static Method m3;
  private static Method m2;
  private static Method m0;
 
  // 代理類的構造函數,其參數正是是InvocationHandler實例,Proxy.newInstance方法就是通過通過這個構造函數來創建代理實例的
  public $Proxy0(InvocationHandler paramInvocationHandler)
    throws 
  {
    super(paramInvocationHandler);
  }
 
  // 以下Object中的三個方法
  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 void sayHello()
    throws 
  {
    try
    {
      this.h.invoke(this, m3, null);
      return;
    }
    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 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") });
      m3 = Class.forName("com.jpeony.spring.proxy.jdk.IHello").getMethod("sayHello", new Class[0]);
      m2 = Class.forName("java.lang.Object").getMethod("toString", new Class[0]);
      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());
    }
  }
}

當代理對象生成後,最後由InvocationHandler的invoke()方法調用目標方法:在動態代理中InvocationHandler是核心,每個代理實例都具有一個關聯的調用處理程。對代理實例調用方法時,將對方法調用進行編碼並將其指派到它的調用處理程序的invoke()方法。所以對代理方法的調用都是通InvocationHadlerinvoke來實現中,而invoke方法根據傳入的代理對象、方法和參數來決定調用代理的哪個方法,其方法簽名如下:

  • invoke(Object Proxy,Method method,Object[] args)

通過反編譯源碼分析調用invoke()過程:從反編譯後的源碼看$Proxy0類繼承了Proxy類,同時實現了IHello接口,即代理類接口,所以才能強制將代理對象轉換爲IHello接口,然後調用$Proxy0中的sayHello()方法。$Proxy0sayHello()源碼:

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

其中,this.h.invoke(this, m3, null)中的this就是$Proxy0對象;m3就是m3 = Class.forName("com.jpeony.spring.proxy.jdk.IHello").getMethod("sayHello", new Class[0]),即是通過全路徑名,反射獲取的目標對象中的真實方法加參數;h就是Proxy類中的變量protected InvocationHandler h;,所以成功的調到了InvocationHandler中的invoke()方法,但是invoke()方法在我們自定義的MyInvocationHandler中實現,MyInvocationHandler中的invoke()方法:

@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("------插入前置通知代碼-------------");
        // 執行相應的目標方法
        Object rs = method.invoke(target,args);
        System.out.println("------插入後置處理代碼-------------");
        return rs;
}

所以,繞了半天,終於調用到了MyInvocationHandler中的invoke()方法,從上面的this.h.invoke(this, m3, null)可以看出,MyInvocationHandlerinvoke第一個參數爲$Proxy0(代理對象),第二個參數爲目標類的真實方法,第三個參數爲目標方法參數,因爲sayHello()沒有參數,所以是null

到這裏,我們真正的實現了通過代理調用目標對象的完全分析,至於InvocationHandler中的invoke()方法就是最後執行了目標方法。到此完成了代理對象生成,目標方法調用。

所以,我們可以看到在打印目標方法調用輸出結果前後所插入的前置和後置代碼處理。

CGLIB 動態代理

CGLIB(Code Generation Library)是一個開源項目,其是一個強大的,高性能,高質量的 Code 生成類庫,它可以在運行期擴展 Java 類與實現 Java 接口。Hibernate 用它來實現 PO(Persistent Object,持久化對象)字節碼的動態生成。

CGLIB 是一個強大的高性能的代碼生成包。它廣泛的被許多 AOP 的框架使用,例如 Spring AOP 爲他們提供方法的interception(攔截)。CGLIB 包的底層是通過使用一個小而快的字節碼處理框架 ASM,來轉換字節碼並生成新的類。

除了 CGLIB 包,腳本語言例如 Groovy 和 BeanShell,也是使用 ASM 來生成 Java 的字節碼。當然不鼓勵直接使用 ASM,因爲它要求你必須對 JVM 內部結構包括class文件的格式和指令集都很熟悉。

代碼示例

實現一個業務類,注意,這個業務類並沒有實現任何接口:

public class HelloService {
 
    public HelloService() {
        System.out.println("HelloService構造");
    }
 
    /**
     * 該方法不能被子類覆蓋,Cglib是無法代理final修飾的方法的
     */
    final public String sayOthers(String name) {
        System.out.println("HelloService:sayOthers>>"+name);
        return null;
    }
 
    public void sayHello() {
        System.out.println("HelloService:sayHello");
    }
}

自定義MethodInterceptor

import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
 
import java.lang.reflect.Method;
 
/**
 * 自定義MethodInterceptor
 */
public class MyMethodInterceptor implements MethodInterceptor{
 
    /**
     * sub:cglib生成的代理對象
     * method:被代理對象方法
     * objects:方法入參
     * methodProxy: 代理方法
     */
    @Override
    public Object intercept(Object sub, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("======插入前置通知======");
        Object object = methodProxy.invokeSuper(sub, objects);
        System.out.println("======插入後者通知======");
        return object;
    }
}

生成 CGLIB 代理對象調用目標方法:

import net.sf.cglib.core.DebuggingClassWriter;
import net.sf.cglib.proxy.Enhancer;
 
public class Client {
    public static void main(String[] args) {
        // 代理類class文件存入本地磁盤方便我們反編譯查看源碼
        System.setProperty(DebuggingClassWriter.DEBUG_LOCATION_PROPERTY, "D:\\code");
        // 通過CGLIB動態代理獲取代理對象的過程
        Enhancer enhancer = new Enhancer();
        // 設置enhancer對象的父類
        enhancer.setSuperclass(HelloService.class);
        // 設置enhancer的回調對象
        enhancer.setCallback(new MyMethodInterceptor());
        // 創建代理對象
        HelloService proxy= (HelloService)enhancer.create();
        // 通過代理對象調用目標方法
        proxy.sayHello();
    }
}

運行上述測試類,其結果如下圖所示:
cglib-proxy-test

源碼分析

實現 CGLIB 動態代理必須實現MethodInterceptor(方法攔截器)接口,源碼如下:

/*
 * Copyright 2002,2003 The Apache Software Foundation
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.sf.cglib.proxy;
 
/**
 * General-purpose {@link Enhancer} callback which provides for "around advice".
 * @author Juozas Baliuka <a href="mailto:[email protected]">[email protected]</a>
 * @version $Id: MethodInterceptor.java,v 1.8 2004/06/24 21:15:20 herbyderby Exp $
 */
public interface MethodInterceptor
extends Callback
{
    /**
     * All generated proxied methods call this method instead of the original method.
     * The original method may either be invoked by normal reflection using the Method object,
     * or by using the MethodProxy (faster).
     * @param obj "this", the enhanced object
     * @param method intercepted Method
     * @param args argument array; primitive types are wrapped
     * @param proxy used to invoke super (non-intercepted method); may be called
     * as many times as needed
     * @throws Throwable any exception may be thrown; if so, super method will not be invoked
     * @return any value compatible with the signature of the proxied method. Method returning void will ignore this value.
     * @see MethodProxy
     */    
    public Object intercept(Object obj, java.lang.reflect.Method method, 
    							Object[] args,
                                MethodProxy proxy) throws Throwable;
}

這個接口只有一個intercept()方法,這個方法有 4 個參數,分別爲:

  • obj表示增強的對象,即實現這個接口類的一個對象;
  • method表示要被攔截的方法;
  • args表示要被攔截方法的參數;
  • proxy表示要觸發父類的方法對象。

在上面的Client代碼中,通過Enhancer.create()方法創建代理對象,create()方法的源碼:

	/**
     * Generate a new class if necessary and uses the specified
     * callbacks (if any) to create a new object instance.
     * Uses the no-arg constructor of the superclass.
     * @return a new instance
     */
    public Object create() {
        classOnly = false;
        argumentTypes = null;
        return createHelper();
	}

該方法含義就是如果有必要就創建一個新類,並且用指定的回調對象創建一個新的對象實例,使用的父類的參數的構造方法來實例化父類的部分。核心內容在createHelper()中,源碼如下:

private Object createHelper() {
        preValidate();
        Object key = KEY_FACTORY.newInstance((superclass != null) ? superclass.getName() : null,
                ReflectUtils.getNames(interfaces),
                filter == ALL_ZERO ? null : new WeakCacheKey<CallbackFilter>(filter),
                callbackTypes,
                useFactory,
                interceptDuringConstruction,
                serialVersionUID);
        this.currentKey = key;
        Object result = super.create(key);
        return result;
}

其中,preValidate()方法校驗callbackTypesfilter是否爲空,以及爲空時的處理。通過newInstance()方法創建EnhancerKey對象,作爲Enhancer父類AbstractClassGenerator.create()方法創建代理對象的參數。

protected Object create(Object key) {
        try {
            ClassLoader loader = getClassLoader();
            Map<ClassLoader, ClassLoaderData> cache = CACHE;
            ClassLoaderData data = cache.get(loader);
            if (data == null) {
                synchronized (AbstractClassGenerator.class) {
                    cache = CACHE;
                    data = cache.get(loader);
                    if (data == null) {
                        Map<ClassLoader, ClassLoaderData> newCache = new WeakHashMap<ClassLoader, ClassLoaderData>(cache);
                        data = new ClassLoaderData(loader);
                        newCache.put(loader, data);
                        CACHE = newCache;
                    }
                }
            }
            this.key = key;
            Object obj = data.get(this, getUseCache());
            if (obj instanceof Class) {
                return firstInstance((Class) obj);
            }
            return nextInstance(obj);
        } catch (RuntimeException e) {
            throw e;
        } catch (Error e) {
            throw e;
        } catch (Exception e) {
            throw new CodeGenerationException(e);
        }
}

真正創建代理對象方法在nextInstance()方法中,該方法爲抽象類AbstractClassGenerator的一個方法,簽名如下:

  • abstract protected Object nextInstance(Object instance) throws Exception;

在子類Enhancer中實現,實現源碼如下:

protected Object nextInstance(Object instance) {
        EnhancerFactoryData data = (EnhancerFactoryData) instance;
 
        if (classOnly) {
            return data.generatedClass;
        }
 
        Class[] argumentTypes = this.argumentTypes;
        Object[] arguments = this.arguments;
        if (argumentTypes == null) {
            argumentTypes = Constants.EMPTY_CLASS_ARRAY;
            arguments = null;
        }
        return data.newInstance(argumentTypes, arguments, callbacks);
}

看看data.newInstance(argumentTypes, arguments, callbacks)方法,第一個參數爲代理對象的構成器類型,第二個爲代理對象構造方法參數,第三個爲對應回調對象。最後根據這些參數,通過反射生成代理對象,源碼如下:

/**
         * Creates proxy instance for given argument types, and assigns the callbacks.
         * Ideally, for each proxy class, just one set of argument types should be used,
         * otherwise it would have to spend time on constructor lookup.
         * Technically, it is a re-implementation of {@link Enhancer#createUsingReflection(Class)},
         * with "cache {@link #setThreadCallbacks} and {@link #primaryConstructor}"
         *
         * @see #createUsingReflection(Class)
         * @param argumentTypes constructor argument types
         * @param arguments constructor arguments
         * @param callbacks callbacks to set for the new instance
         * @return newly created proxy
         */
        public Object newInstance(Class[] argumentTypes, Object[] arguments, Callback[] callbacks) {
            setThreadCallbacks(callbacks);
            try {
                // Explicit reference equality is added here just in case Arrays.equals does not have one
                if (primaryConstructorArgTypes == argumentTypes ||
                        Arrays.equals(primaryConstructorArgTypes, argumentTypes)) {
                    // If we have relevant Constructor instance at hand, just call it
                    // This skips "get constructors" machinery
                    return ReflectUtils.newInstance(primaryConstructor, arguments);
                }
                // Take a slow path if observing unexpected argument types
                return ReflectUtils.newInstance(generatedClass, argumentTypes, arguments);
            } finally {
                // clear thread callbacks to allow them to be gc'd
                setThreadCallbacks(null);
            }
 }

最後生成代理對象:

hello-service-proxy-class
將其反編譯後代碼如下:

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
 
import java.lang.reflect.Method;
import net.sf.cglib.core.ReflectUtils;
import net.sf.cglib.core.Signature;
import net.sf.cglib.proxy.Callback;
import net.sf.cglib.proxy.Factory;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
 
public class HelloService$$EnhancerByCGLIB$$be45efdd extends HelloService implements Factory {
    private boolean CGLIB$BOUND;
    public static Object CGLIB$FACTORY_DATA;
    private static final ThreadLocal CGLIB$THREAD_CALLBACKS;
    private static final Callback[] CGLIB$STATIC_CALLBACKS;
    private MethodInterceptor CGLIB$CALLBACK_0;
    private static Object CGLIB$CALLBACK_FILTER;
    private static final Method CGLIB$sayHello$0$Method;
    private static final MethodProxy CGLIB$sayHello$0$Proxy;
    private static final Object[] CGLIB$emptyArgs;
    private static final Method CGLIB$equals$1$Method;
    private static final MethodProxy CGLIB$equals$1$Proxy;
    private static final Method CGLIB$toString$2$Method;
    private static final MethodProxy CGLIB$toString$2$Proxy;
    private static final Method CGLIB$hashCode$3$Method;
    private static final MethodProxy CGLIB$hashCode$3$Proxy;
    private static final Method CGLIB$clone$4$Method;
    private static final MethodProxy CGLIB$clone$4$Proxy;
 
    static void CGLIB$STATICHOOK1() {
        CGLIB$THREAD_CALLBACKS = new ThreadLocal();
        CGLIB$emptyArgs = new Object[0];
        Class var0 = Class.forName("com.jpeony.spring.proxy.cglib.HelloService$$EnhancerByCGLIB$$be45efdd");
        Class var1;
        Method[] var10000 = ReflectUtils.findMethods(new String[]{"equals", "(Ljava/lang/Object;)Z", "toString", "()Ljava/lang/String;", "hashCode", "()I", "clone", "()Ljava/lang/Object;"}, (var1 = Class.forName("java.lang.Object")).getDeclaredMethods());
        CGLIB$equals$1$Method = var10000[0];
        CGLIB$equals$1$Proxy = MethodProxy.create(var1, var0, "(Ljava/lang/Object;)Z", "equals", "CGLIB$equals$1");
        CGLIB$toString$2$Method = var10000[1];
        CGLIB$toString$2$Proxy = MethodProxy.create(var1, var0, "()Ljava/lang/String;", "toString", "CGLIB$toString$2");
        CGLIB$hashCode$3$Method = var10000[2];
        CGLIB$hashCode$3$Proxy = MethodProxy.create(var1, var0, "()I", "hashCode", "CGLIB$hashCode$3");
        CGLIB$clone$4$Method = var10000[3];
        CGLIB$clone$4$Proxy = MethodProxy.create(var1, var0, "()Ljava/lang/Object;", "clone", "CGLIB$clone$4");
        CGLIB$sayHello$0$Method = ReflectUtils.findMethods(new String[]{"sayHello", "()V"}, (var1 = Class.forName("com.jpeony.spring.proxy.cglib.HelloService")).getDeclaredMethods())[0];
        CGLIB$sayHello$0$Proxy = MethodProxy.create(var1, var0, "()V", "sayHello", "CGLIB$sayHello$0");
    }
 
    final void CGLIB$sayHello$0() {
        super.sayHello();
    }
 
    public final void sayHello() {
        MethodInterceptor var10000 = this.CGLIB$CALLBACK_0;
        if (var10000 == null) {
            CGLIB$BIND_CALLBACKS(this);
            var10000 = this.CGLIB$CALLBACK_0;
        }
 
        if (var10000 != null) {
            var10000.intercept(this, CGLIB$sayHello$0$Method, CGLIB$emptyArgs, CGLIB$sayHello$0$Proxy);
        } else {
            super.sayHello();
        }
    }
 
    final boolean CGLIB$equals$1(Object var1) {
        return super.equals(var1);
    }
 
    public final boolean equals(Object var1) {
        MethodInterceptor var10000 = this.CGLIB$CALLBACK_0;
        if (var10000 == null) {
            CGLIB$BIND_CALLBACKS(this);
            var10000 = this.CGLIB$CALLBACK_0;
        }
 
        if (var10000 != null) {
            Object var2 = var10000.intercept(this, CGLIB$equals$1$Method, new Object[]{var1}, CGLIB$equals$1$Proxy);
            return var2 == null ? false : (Boolean)var2;
        } else {
            return super.equals(var1);
        }
    }
 
    final String CGLIB$toString$2() {
        return super.toString();
    }
 
    public final String toString() {
        MethodInterceptor var10000 = this.CGLIB$CALLBACK_0;
        if (var10000 == null) {
            CGLIB$BIND_CALLBACKS(this);
            var10000 = this.CGLIB$CALLBACK_0;
        }
 
        return var10000 != null ? (String)var10000.intercept(this, CGLIB$toString$2$Method, CGLIB$emptyArgs, CGLIB$toString$2$Proxy) : super.toString();
    }
 
    final int CGLIB$hashCode$3() {
        return super.hashCode();
    }
 
    public final int hashCode() {
        MethodInterceptor var10000 = this.CGLIB$CALLBACK_0;
        if (var10000 == null) {
            CGLIB$BIND_CALLBACKS(this);
            var10000 = this.CGLIB$CALLBACK_0;
        }
 
        if (var10000 != null) {
            Object var1 = var10000.intercept(this, CGLIB$hashCode$3$Method, CGLIB$emptyArgs, CGLIB$hashCode$3$Proxy);
            return var1 == null ? 0 : ((Number)var1).intValue();
        } else {
            return super.hashCode();
        }
    }
 
    final Object CGLIB$clone$4() throws CloneNotSupportedException {
        return super.clone();
    }
 
    protected final Object clone() throws CloneNotSupportedException {
        MethodInterceptor var10000 = this.CGLIB$CALLBACK_0;
        if (var10000 == null) {
            CGLIB$BIND_CALLBACKS(this);
            var10000 = this.CGLIB$CALLBACK_0;
        }
 
        return var10000 != null ? var10000.intercept(this, CGLIB$clone$4$Method, CGLIB$emptyArgs, CGLIB$clone$4$Proxy) : super.clone();
    }
 
    public static MethodProxy CGLIB$findMethodProxy(Signature var0) {
        String var10000 = var0.toString();
        switch(var10000.hashCode()) {
        case -508378822:
            if (var10000.equals("clone()Ljava/lang/Object;")) {
                return CGLIB$clone$4$Proxy;
            }
            break;
        case 1535311470:
            if (var10000.equals("sayHello()V")) {
                return CGLIB$sayHello$0$Proxy;
            }
            break;
        case 1826985398:
            if (var10000.equals("equals(Ljava/lang/Object;)Z")) {
                return CGLIB$equals$1$Proxy;
            }
            break;
        case 1913648695:
            if (var10000.equals("toString()Ljava/lang/String;")) {
                return CGLIB$toString$2$Proxy;
            }
            break;
        case 1984935277:
            if (var10000.equals("hashCode()I")) {
                return CGLIB$hashCode$3$Proxy;
            }
        }
 
        return null;
    }
 
    public HelloService$$EnhancerByCGLIB$$be45efdd() {
        CGLIB$BIND_CALLBACKS(this);
    }
 
    public static void CGLIB$SET_THREAD_CALLBACKS(Callback[] var0) {
        CGLIB$THREAD_CALLBACKS.set(var0);
    }
 
    public static void CGLIB$SET_STATIC_CALLBACKS(Callback[] var0) {
        CGLIB$STATIC_CALLBACKS = var0;
    }
 
    private static final void CGLIB$BIND_CALLBACKS(Object var0) {
        HelloService$$EnhancerByCGLIB$$be45efdd var1 = (HelloService$$EnhancerByCGLIB$$be45efdd)var0;
        if (!var1.CGLIB$BOUND) {
            var1.CGLIB$BOUND = true;
            Object var10000 = CGLIB$THREAD_CALLBACKS.get();
            if (var10000 == null) {
                var10000 = CGLIB$STATIC_CALLBACKS;
                if (var10000 == null) {
                    return;
                }
            }
 
            var1.CGLIB$CALLBACK_0 = (MethodInterceptor)((Callback[])var10000)[0];
        }
 
    }
 
    public Object newInstance(Callback[] var1) {
        CGLIB$SET_THREAD_CALLBACKS(var1);
        HelloService$$EnhancerByCGLIB$$be45efdd var10000 = new HelloService$$EnhancerByCGLIB$$be45efdd();
        CGLIB$SET_THREAD_CALLBACKS((Callback[])null);
        return var10000;
    }
 
    public Object newInstance(Callback var1) {
        CGLIB$SET_THREAD_CALLBACKS(new Callback[]{var1});
        HelloService$$EnhancerByCGLIB$$be45efdd var10000 = new HelloService$$EnhancerByCGLIB$$be45efdd();
        CGLIB$SET_THREAD_CALLBACKS((Callback[])null);
        return var10000;
    }
 
    public Object newInstance(Class[] var1, Object[] var2, Callback[] var3) {
        CGLIB$SET_THREAD_CALLBACKS(var3);
        HelloService$$EnhancerByCGLIB$$be45efdd var10000 = new HelloService$$EnhancerByCGLIB$$be45efdd;
        switch(var1.length) {
        case 0:
            var10000.<init>();
            CGLIB$SET_THREAD_CALLBACKS((Callback[])null);
            return var10000;
        default:
            throw new IllegalArgumentException("Constructor not found");
        }
    }
 
    public Callback getCallback(int var1) {
        CGLIB$BIND_CALLBACKS(this);
        MethodInterceptor var10000;
        switch(var1) {
        case 0:
            var10000 = this.CGLIB$CALLBACK_0;
            break;
        default:
            var10000 = null;
        }
 
        return var10000;
    }
 
    public void setCallback(int var1, Callback var2) {
        switch(var1) {
        case 0:
            this.CGLIB$CALLBACK_0 = (MethodInterceptor)var2;
        default:
        }
    }
 
    public Callback[] getCallbacks() {
        CGLIB$BIND_CALLBACKS(this);
        return new Callback[]{this.CGLIB$CALLBACK_0};
    }
 
    public void setCallbacks(Callback[] var1) {
        this.CGLIB$CALLBACK_0 = (MethodInterceptor)var1[0];
    }
 
    static {
        CGLIB$STATICHOOK1();
    }
}

重點關注代理對象的sayHello方法:

    public final void sayHello() {
        MethodInterceptor var10000 = this.CGLIB$CALLBACK_0;
        if (var10000 == null) {
            CGLIB$BIND_CALLBACKS(this);
            var10000 = this.CGLIB$CALLBACK_0;
        }
 
        if (var10000 != null) {
            var10000.intercept(this, CGLIB$sayHello$0$Method, CGLIB$emptyArgs, CGLIB$sayHello$0$Proxy);
        } else {
            super.sayHello();
        }
    }

從代理對象反編譯源碼可以知道,代理對象繼承於HelloService,攔截器調用intercept()方法,intercept()方法由自定義MyMethodInterceptor實現,所以最後調用MyMethodInterceptor中的intercept()方法,從而完成了由代理對象訪問到目標對象的動態代理實現。

JDK 和 CGLIB 動態代理的區別

主要區別

  • JDK 動態代理:利用攔截器(攔截器必須實現InvocationHanlder)加上反射機制生成一個實現代理接口的匿名類,在調用具體方法前調用InvokeHandler來處理。
  • CGLIB 動態代理:利用 ASM 開源包,對代理對象類的class文件加載進來,通過修改其字節碼生成子類來處理。

那麼,何時使用 JDK 還是 CGLIB 動態代理呢?

  • 如果目標對象實現了接口,默認情況下會採用 JDK 的動態代理實現 AOP。
  • 如果目標對象實現了接口,可以強制使用 CGLIB 實現 AOP。
  • 如果目標對象沒有實現了接口,必須採用 CGLIB 庫,Spring 會自動在 JDK 動態代理和 CGLIB 之間轉換。

更近一步,如何強制使用 CGLIB 實現 AOP 呢?

  1. 添加 CGLIB 庫,如aspectjrt-xxx.jaraspectjweaver-xxx.jarcglib-nodep-xxx.jar
  2. 在 Spring 配置文件中加入<aop:aspectj-autoproxy proxy-target-class="true"/>

除此之外,JDK 和 CGLIB 動態代理字節碼生成的區別是?

  • JDK 動態代理只能對實現了接口的類生成代理,而不能針對類。
  • CGLIB 是針對類實現代理,主要是對指定的類生成一個子類,覆蓋其中的方法,並覆蓋其中方法實現增強,但是因爲採用的是繼承,所以該類或方法最好不要聲明成final,對於final類或方法,是無法繼承的。

還有一個大家比較關心的問題,那就是 JDK 和 CGLIB 哪個速度更快?

  • 使用 CGLIB 實現動態代理,CGLIB 底層採用 ASM 字節碼生成框架,使用字節碼技術生成代理類,在 JDK 6 之前比使用 Java 反射效率要高。唯一需要注意的是,CGLIB 不能對聲明爲final的方法進行代理,因爲 CGLIB 原理是動態生成被代理類的子類。
  • 在 JDK 6 之後逐步對 JDK 動態代理優化之後,在調用次數較少的情況下,JDK 代理效率高於 CGLIB 代理效率,只有當進行大量調用的時候,JDK 6 和 JDK 7 比 CGLIB 代理效率低一點,但是到 JDK 8 的時候,JDK 代理效率高於 CGLIB 代理。
  • 總之,每一次 JDK 版本升級,JDK 代理效率都得到提升,而 CGLIB 代理消息確有點跟不上步伐。

作爲我們開發中常用的框架,Spring 是如何選擇用 JDK 還是 CGLIB 的呢?

  • 當 Bean 實現接口時,Spring 就會用 JDK 的動態代理
  • 當 Bean 沒有實現接口時,Spring 使用 CGLIB 是實現
  • 可以強制使用 CGLIB,在 Spring 配置中加入<aop:aspectj-autoproxy proxy-target-class="true"/>

代碼示例

  • 接口
/**
 * 用戶管理接口(真實主題和代理主題的共同接口,這樣在任何可以使用真實主題的地方都可以使用代理主題代理。)
 * --被代理接口定義
 */
public interface IUserManager {
    void addUser(String id, String password);
}
  • 接口實現類
/**
 * 用戶管理接口實現(被代理的實現類)
 */
public class UserManagerImpl implements IUserManager {
 
    @Override
    public void addUser(String id, String password) {
        System.out.println("======調用了UserManagerImpl.addUser()方法======");
    }
}
  • JDK 動態代理實現
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
 
/**
 * JDK動態代理類
 */
public class JDKProxy implements InvocationHandler {
    /** 需要代理的目標對象 */
    private Object targetObject;
 
    /**
     * 將目標對象傳入進行代理
     */
    public Object newProxy(Object targetObject) {
        this.targetObject = targetObject;
        //返回代理對象
        return Proxy.newProxyInstance(targetObject.getClass().getClassLoader(),
                targetObject.getClass().getInterfaces(), this);
    }
 
    /**
     * invoke方法
     */
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        // 一般我們進行邏輯處理的函數比如這個地方是模擬檢查權限
        checkPopedom();
        // 設置方法的返回值
        Object ret = null;
        // 調用invoke方法,ret存儲該方法的返回值
        ret  = method.invoke(targetObject, args);
        return ret;
    }
 
    /**
     * 模擬檢查權限的例子
     */
    private void checkPopedom() {
        System.out.println("======檢查權限checkPopedom()======");
    }
}
  • CGLIB 動態代理實現:
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
 
import java.lang.reflect.Method;
 
/**
 * CGLibProxy動態代理類
 */
public class CGLibProxy implements MethodInterceptor {
    /** CGLib需要代理的目標對象 */
    private Object targetObject;
 
    public Object createProxyObject(Object obj) {
        this.targetObject = obj;
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(obj.getClass());
        enhancer.setCallback(this);
        Object proxyObj = enhancer.create();
        // 返回代理對象
        return proxyObj;
    }
 
    @Override
    public Object intercept(Object proxy, Method method, Object[] args,
                            MethodProxy methodProxy) throws Throwable {
        Object obj = null;
        // 過濾方法
        if ("addUser".equals(method.getName())) {
            // 檢查權限
            checkPopedom();
        }
        obj = method.invoke(targetObject, args);
        return obj;
    }
 
    private void checkPopedom() {
        System.out.println("======檢查權限checkPopedom()======");
    }
}
  • 客戶端測試類
/**
 * 代理模式[[ 客戶端--》代理對象--》目標對象 ]]
 */
public class Client {
    public static void main(String[] args) {
        System.out.println("**********************CGLibProxy**********************");
        CGLibProxy cgLibProxy = new CGLibProxy();
        IUserManager userManager = (IUserManager) cgLibProxy.createProxyObject(new UserManagerImpl());
        userManager.addUser("jpeony", "123456");
 
        System.out.println("**********************JDKProxy**********************");
        JDKProxy jdkPrpxy = new JDKProxy();
        IUserManager userManagerJDK = (IUserManager) jdkPrpxy.newProxy(new UserManagerImpl());
        userManagerJDK.addUser("jpeony", "123456");
    }
}

運行上述測試類,其結果如下圖所示:

proxy-test

總結

JDK 動態代理不需要第三方庫支持,只需要 JDK 環境就可以進行代理,使用條件:

  • 實現InvocationHandler
  • 使用Proxy.newProxyInstance產生代理對象
  • 被代理的對象必須要實現接口

CGLIB 必須依賴於 CGLIB 的類庫,其爲需要被代理的類生成一個子類,覆蓋其中的方法,實際上是一種繼承。


參考資料

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章