Java--JDK動態代理核心源碼解析,java--jdk源碼

來源:互聯網
上載者:User

Java--JDK動態代理核心源碼解析,java--jdk源碼

1、首先我們瞭解一下JDK動態代理的使用方法:

    public static void main(String[] args) {        /**         * 建立一個Bean對象,該對象實現BeanInterFace介面         */        BeanInterFace bean = new Bean();        /**         * 建立一個MyProxy對象,該對象實現InvocationHandler介面,將bean注入到MyProxy中         */        InvocationHandler invocationHandler = new MyProxy(bean);        /**         * 調用JDK的Proxy類,使用newProxyInstance方法,直接產生Bean對象的代理對象         * 注意:Classloader必須採用實際代理對象的ClassLoader,否則會出現反覆調用的問題         */        BeanInterFace beanProxy = (BeanInterFace) Proxy.newProxyInstance(bean.getClass().getClassLoader(),                bean.getClass().getInterfaces(),invocationHandler);        /**         * 使用代理對象         */        System.out.println(beanProxy.getClass().getName());        beanProxy.say();    }

 

2、我們看一下JDK源碼,是如何?動態代理的

Proxy.newProxyInstance最終會調用Proxy.ProxyClassFactory.apply()方法組建代理程式Class

         //建立proxyname,通過package+ClassName+編號
        String proxyName = proxyPkg + proxyClassNamePrefix + num; /* * 這裡產生了代理的Class,並編譯返回二進位byte[]數組 */ byte[] proxyClassFile = ProxyGenerator.generateProxyClass( proxyName, interfaces, accessFlags); try {
//這裡載入了ProxyClass,這裡的載入用的是系統appClassLoader,至今我還沒明白怎麼才能使用,JDK使用的native方法 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()); }

 

3、具體proxyClass是如何產生的

大致就是:

proxyClass有一個建構函式,該建構函式的參數為InvocationHandler介面,proxyClass執行個體化以後將InvocationHandler的引用儲存在自己的屬性中,然後proxyClass每個方法的觸發都會觸發InvocationHandler的invoke方法,通過反射調用真實對象的的方法。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.