java動態代理的實現以及原理


1.前言

之前對動態代理的技術只是表面上理解,沒有形成一個體系,這里總結一下,整個動態代理的實現以及實現原理,以表述的更清楚一些。

2.動態代理的實現應用到的技術

1、動態編譯技術,可以使用Java自帶的JavaCompiler類,也可以使用CGLIB、ASM等字節碼增強技術,Java的動態代理包括Spring的內部實現貌似用的都是這個

2、反射,包括對於類.class和getClass()方法的理解,Method類、Constructor類的理解

3、IO流,主要就是字符輸出流FileWriter

4、對於ClassLoader的理解

3.動態代理示例

接口類:

public interface UserService {  
    public abstract void add(); 
    public abstract void update();
}

接口實現類:

public class UserServiceImpl implements UserService {  
  
     public void add() {  
        System.out.println("----- add -----");  
    }
    
    public void update(){
    	 System.out.println("----- update-----");  
    }
}

代理處理類MyInvocationHandler.java

import java.lang.reflect.InvocationHandler;  
import java.lang.reflect.Method;  
import java.lang.reflect.Proxy;  
  
public class MyInvocationHandler implements InvocationHandler {  
  
    private Object target;  
  
    public MyInvocationHandler(Object target) {  
        super();  
        this.target = target;  
    }  
  
    public Object getProxy() {  
        return Proxy.newProxyInstance(Thread.currentThread()  
                .getContextClassLoader(), target.getClass().getInterfaces(),  
                this);  
    }  
  
    @Override  
    public Object invoke(Object proxy, Method method, Object[] args)  
            throws Throwable {  
        System.out.println("----- before -----");  
        Object result = method.invoke(target, args);  
        System.out.println("----- after -----");  
        return result;  
    }  
}  

 測試類:

public class DynamicProxyTest {  
  
    public static void main(String[] args) {  
        UserService userService = new UserServiceImpl();  
        MyInvocationHandler invocationHandler = new MyInvocationHandler(  
                userService);  
  
        UserService proxy = (UserService) invocationHandler.getProxy();  
        proxy.add();
        proxy.update();
    }  
}  

 輸出:

----- before -----
----- add -----
----- after -----
----- before -----
----- update -----
----- after -----

用起來是很簡單,其實這里基本上就是AOP的一個簡單實現了,目的是在目標對象的方法執行之前和執行之后進行了增強。

Spring的AOP實現其實也是用了Proxy和InvocationHandler這兩個東西的。 

4.動態代理原理

下面我們從jdk實現的源代碼的層面分析一下,動態代理產生的整個過程。

上面的程序的入口,便是代理處理類MyInvocationHandler中的getProxy()方法。

 public Object getProxy() {  
        return Proxy.newProxyInstance(Thread.currentThread()  
                .getContextClassLoader(), target.getClass().getInterfaces(),  
                this);  
 }

Proxy.newProxyInstance() 方法,最終將返回一個實現了指定接口的類的實例,

其三個參數分別是:ClassLoader,指定的接口及我們自己定義的InvocationHandler類。我摘幾條關鍵的代碼出來,看看這個代理類的實例對象到底是怎么生成的。

4.1 Proxy.newProxyInstance的源碼(JDK1.6):

public static Object newProxyInstance(ClassLoader loader,
					  Class<?>[] interfaces,
					  InvocationHandler h)
	throws IllegalArgumentException
    {
	if (h == null) {
	    throw new NullPointerException();
	}

	/*
	 * Look up or generate the designated proxy class.
	 */
       //getProxyClass獲得這個代理類
        Class<?> cl = getProxyClass0(loader, interfaces); // stack walk magic: do not refactor

	/*
	 * Invoke its constructor with the designated invocation handler.
	 */
	try {
            //然后通過c1.getConstructor()拿到構造函數
            final Constructor<?> cons = cl.getConstructor(constructorParams);
            final InvocationHandler ih = h;
            SecurityManager sm = System.getSecurityManager();
            if (sm != null && ProxyAccessHelper.needsNewInstanceCheck(cl)) {
                // create proxy instance with doPrivilege as the proxy class may
                // implement non-public interfaces that requires a special permission
                return AccessController.doPrivileged(new PrivilegedAction<Object>() {
                    public Object run() {
                        //通過cons.newInstance返回這個新的代理類的一個實例,注意:調用newInstance的時候,傳入的參數為h,即我們自己定義好的InvocationHandler類
                        return newInstance(cons, ih);
                    }
                });
            } else {
                return newInstance(cons, ih);
            }
	} catch (NoSuchMethodException e) {
	    throw new InternalError(e.toString());
	} 
    }

4.2 我們再去看getProxyClass0()方法的源碼:

private static Class<?> getProxyClass0(ClassLoader loader, Class<?>... interfaces) {
        .........省略一些代碼
        // 如果目標類實現的接口數大於65535個則拋出異常(我XX)  
        if (interfaces.length > 65535) {
	    throw new IllegalArgumentException("interface limit exceeded");
	}
        //聲明代理對象的Class對象 
	Class proxyClass = null;

	String[] interfaceNames = new String[interfaces.length];

	Set 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");
	    }

	    /*
	     * JDK里規定了:動態代理 只能針對接口生成代理,不能只針對某一個類生成代理
這也算是一個缺點吧,如果需要對一個類生成代理則可用第三方庫
	     */
	    if (!interfaceClass.isInterface()) {
		throw new IllegalArgumentException(
		    interfaceClass.getName() + " is not an interface");
	    }
           // 把目標類實現的接口代表的Class對象放到Set中 
	    interfaceSet.add(interfaceClass);

	    interfaceNames[i] = interfaceName;
	}

	// 把目標類實現的接口名稱作為緩存(Map)中的key  
	Object key = Arrays.asList(interfaceNames);

	Map cache;
	synchronized (loaderToCache) {
           // 從緩存中獲取cache  
	    cache = (Map) loaderToCache.get(loader);
	    if (cache == null) {
               // 如果獲取不到,則新建地個HashMap實例  
		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) {
		    // 如果代理對象的Class實例已經存在,則直接返回  
		    return proxyClass;
		} else if (value == pendingGenerationMarker) {
		    // proxy class being generated: wait for it
		    try {
			cache.wait();
		    } catch (InterruptedException e) {
		    }
		    continue;
		} else {
		    cache.put(key, pendingGenerationMarker);
		    break;
		}
	    } while (true);
	}
....................省略代碼
try{
               // 這里就是動態生成代理對象的最關鍵的地方:利用ProxyGenerator為我們生成了最終代理類的字節碼文件
		byte[] proxyClassFile =ProxyGenerator.generateProxyClass(proxyName,Interfaces);
		try {
               // 根據代理類的字節碼生成代理類的實例
		    proxyClass = defineClass0(loader, proxyName,
			proxyClassFile, 0, proxyClassFile.length);
		} catch (ClassFormatError e) {
		    throw new IllegalArgumentException(e.toString());
		}
	    }
	    proxyClasses.put(proxyClass, null);

	} finally {
	return proxyClass;
    }        

4.3 其中ProxyGenerator.generateProxyClass()的方法是最終生成代理類的字節碼.

ProxyGenerator是sun.misc包中的類,它沒有開源,不過我們可以根據它將生成的代理類的字節碼保存在本地上,然后反編譯查看生成的代理類。

具體請參照地址:http://blog.csdn.net/mhmyqn/article/details/48474815

4.4 反編譯生成的$Proxy0.class代理類文件

下面從網上copy的一個代理類的反編譯文件,對比可以看一下:

package com.sun.proxy;  
  
import com.mikan.proxy.HelloWorld;  
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 HelloWorld {  
  private static Method m1;  
  private static Method m3;  
  private static Method m0;  
  private static Method m2;  
  //這個就是 上面newInstance()方法中傳入的代理實現類MyInvocationHandler,而這個類在代理類中的變量名為this.h
  public $Proxy0(InvocationHandler paramInvocationHandler) {  
    super(paramInvocationHandler);  
  }  
  
  public final boolean equals(Object paramObject) {  
    try {  
      return ((Boolean)this.h.invoke(this, m1, new Object[] { paramObject })).booleanValue();  
    }  
    catch (Error|RuntimeException localError) {  
      throw localError;  
    }  
    catch (Throwable localThrowable) {  
      throw new UndeclaredThrowableException(localThrowable);  
    }  
  }  
  //重點就是這里,代理類的
  public final void sayHello(String paramString) {  
    try {
//見上面構造方法,this.h 就代表MyInvocationHandler類,所以執行的就是我們代理實現類中的invoke方法。 this.h.invoke(this, m3, new Object[] { paramString }); return; } catch (Error|RuntimeException localError) { throw localError; } catch (Throwable localThrowable) { throw new UndeclaredThrowableException(localThrowable); } } public final int hashCode() { try { return ((Integer)this.h.invoke(this, m0, null)).intValue(); } catch (Error|RuntimeException localError) { throw localError; } catch (Throwable localThrowable) { throw new UndeclaredThrowableException(localThrowable); } } public final String toString() { try { return (String)this.h.invoke(this, m2, null); } catch (Error|RuntimeException localError) { throw localError; } 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.mikan.proxy.HelloWorld").getMethod("sayHello", new Class[] { Class.forName("java.lang.String") }); m0 = Class.forName("java.lang.Object").getMethod("hashCode", new Class[0]); m2 = Class.forName("java.lang.Object").getMethod("toString", new Class[0]); return; } catch (NoSuchMethodException localNoSuchMethodException) { throw new NoSuchMethodError(localNoSuchMethodException.getMessage()); } catch (ClassNotFoundException localClassNotFoundException) { throw new NoClassDefFoundError(localClassNotFoundException.getMessage()); } } }

 由此總結一下動態代理實現過程。

1.通過 Proxy.newProxyInstance() 方法,返回一個繼承Proxy類,並且最終實現了指定接口的代理類的實例。

在這里分為兩個大的步驟:

  1. 通過getProxyClass0()方法生成代理類。在這個方法里面,
  • ProxyGenerator.generateProxyClass()的方法是最終生成代理類的字節碼.
  • defineClass0()方法把相應的字節碼生成代理類

         2. 調用 newInstance(Constructor<?> cons, InvocationHandler h)方法 創建一個新的代理類實例,創建對象時,傳入我們定義好的代理處理類,InvocationHandle類。 

2. 調用新實例的方法,即此例中的add(), update()方法,即原InvocationHandler類中的invoke()方法。

5.動態代理的優點

1、最直觀的,類少了很多
2、代理內容也就是InvocationHandler接口的實現類可以復用,可以給A接口用、也可以給B接口用,A接口用了InvocationHandler接口實現類A的代理,不想用了,可以方便地換成InvocationHandler接口實現B的代理
3、最重要的,用了動態代理,就可以在不修改原來代碼的基礎上,就在原來代碼的基礎上做操作,這就是AOP即面向切面編程

6.動態代理的缺點

動態代理的缺點,就是前面我們讀源代碼的時候遇到的。它只能針對接口生成代理,不能只針對某一個類生成代理。

如果需要為某一個單獨的類實現一個代理的話,考慮使用CGLIB等第三方字節碼(一種字節碼增強技術)。

 

參考地址:http://blog.csdn.net/zhangerqing/article/details/42504281/

http://www.cnblogs.com/xrq730/p/4907999.html

http://blog.csdn.net/mhmyqn/article/details/4847481516:23:20

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM