Java - 動態代理

來源:互聯網
上載者:User

標籤:核心   after   必須   rgs   協助文檔   stat   java   main   system   

在學習Spring的時候,我們知道Spring主要有兩大思想,一個是IoC,另一個就是AOP,對於IoC,依賴注入就不用多說了,而對於Spring的核心AOP來說,我們不但要知道怎麼通過AOP來滿足的我們的功能,我們更需要學習的是其底層是怎麼樣的一個原理,而AOP的原理就是java的動態代理機制,所以本篇隨筆就是對java的動態機制進行一個回顧。

在java的動態代理機制中,有兩個重要的類或介面,一個是 InvocationHandler(Interface)、另一個則是 Proxy(Class),這一個類和介面是實現我們動態代理所必須用到的。首先我們先來看看java的API協助文檔是怎麼樣對這兩個類進行描述的:

InvocationHandler:

InvocationHandler is the interface implemented by the invocation handler of a proxy instance. Each proxy instance has an associated invocation handler. When a method is invoked on a proxy instance, the method invocation is encoded and dispatched to the invoke method of its invocation handler.

每一個動態代理類都必須要實現InvocationHandler這個介面,並且每個代理類的執行個體都關聯到了一個handler,當我們通過代理對象調用一個方法的時候,這個方法的調用就會被轉寄為由InvocationHandler這個介面的 invoke 方法來進行調用。我們來看看InvocationHandler這個介面的唯一一個方法 invoke 方法:

Object invoke(Object proxy, Method method, Object[] args) throws Throwable

我們看到這個方法一共接受三個參數,那麼這三個參數分別代表什麼呢?

Object invoke(Object proxy, Method method, Object[] args) throws Throwableproxy:  指代我們所代理的那個真實對象method:  指代的是我們所要調用真實對象的某個方法的Method對象args:  指代的是調用真實對象某個方法時接受的參數

如果不是很明白,等下通過一個執行個體會對這幾個參數進行更深的講解。

接下來我們來看看Proxy這個類:

Proxy provides static methods for creating dynamic proxy classes and instances, and it is also the superclass of all dynamic proxy classes created by those methods. 

Proxy這個類的作用就是用來動態建立一個代理對象的類,它提供了許多的方法,但是我們用的最多的就是 newProxyInstance 這個方法:

public static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces,  InvocationHandler h)  throws IllegalArgumentException
Returns an instance of a proxy class for the specified interfaces that dispatches method invocations to the specified invocation handler.

這個方法的作用就是得到一個動態代理對象,其接收三個參數,我們來看看這三個參數所代表的含義:

public static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h) throws IllegalArgumentExceptionloader:  一個ClassLoader對象,定義了由哪個ClassLoader對象來對產生的代理對象進行載入interfaces:  一個Interface對象的數組,表示的是我將要給我需要代理的對象提供一組什麼介面,如果我提供了一組介面給它,那麼這個代理對象就宣稱實現了該介面(多態),這樣我就能調用這組介面中的方法了h:  一個InvocationHandler對象,表示的是當我這個動態代理對象在調用方法的時候,會關聯到哪一個InvocationHandler對象上

好了,在介紹完這兩個介面(類)以後,我們來通過一個執行個體來看看我們的動態代理模式是什麼樣的:

首先我們定義了一個Subject類型的介面,為其聲明了兩個方法:

public interface Subject{    public void rent();        public void hello(String str);}

接著,定義了一個類來實現這個介面,這個類就是我們的真實對象,RealSubject類:

public class RealSubject implements Subject{    @Override    public void rent()    {        System.out.println("I want to rent my house");    }        @Override    public void hello(String str)    {        System.out.println("hello: " + str);    }}

下一步,我們就要定義一個動態代理類了,前面說個,每一個動態代理類都必須要實現 InvocationHandler 這個介面,因此我們這個動態代理類也不例外:

public class DynamicProxy implements InvocationHandler{    // 這個就是我們要代理的真實對象    private Object subject;        //    構造方法,給我們要代理的真實對象賦初值    public DynamicProxy(Object subject)    {        this.subject = subject;    }        @Override    public Object invoke(Object object, Method method, Object[] args)            throws Throwable    {        //  在代理真實對象前我們可以添加一些自己的操作        System.out.println("before rent house");                System.out.println("Method:" + method);                //    當代理對象調用真實對象的方法時,其會自動的跳轉到代理對象關聯的handler對象的invoke方法來進行調用        method.invoke(subject, args);                //  在代理真實對象後我們也可以添加一些自己的操作        System.out.println("after rent house");                return null;    }}

最後,來看看我們的Client類:

public class Client{    public static void main(String[] args)    {        //    我們要代理的真實對象        Subject realSubject = new RealSubject();        //    我們要代理哪個真實對象,就將該對象傳進去,最後是通過該真實對象來調用其方法的        InvocationHandler handler = new DynamicProxy(realSubject);        /*         * 通過Proxy的newProxyInstance方法來建立我們的代理對象,我們來看看其三個參數         * 第一個參數 handler.getClass().getClassLoader() ,我們這裡使用handler這個類的ClassLoader對象來載入我們的代理對象         * 第二個參數realSubject.getClass().getInterfaces(),我們這裡為代理對象提供的介面是真實對象所實行的介面,表示我要代理的是該真實對象,這樣我就能調用這組介面中的方法了         * 第三個參數handler, 我們這裡將這個代理對象關聯到了上方的 InvocationHandler 這個對象上         */        Subject subject = (Subject)Proxy.newProxyInstance(handler.getClass().getClassLoader(), realSubject                .getClass().getInterfaces(), handler);                System.out.println(subject.getClass().getName());        subject.rent();        subject.hello("world");    }}

 

Java - 動態代理

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.