Java反射機制動態代理

來源:互聯網
上載者:User

標籤:

package com.kaige123;/** * 程式員 * @author 凱哥  */public interface Chengxuyuan {    /**     * 寫代碼方法     */    public void xiedaima();}
package com.kaige123;/** * 程式員介面實作類別 * @author 凱哥 */public class ChengxuyuanImpl implements Chengxuyuan {    public void xiedaima() {         System.out.println("寫代碼...");    } }
package com.kaige123;import java.lang.reflect.InvocationHandler;import java.lang.reflect.Method; /** * 處理類 * @author 凱哥 */public class CxyHandler implements InvocationHandler {    //程式員實現對象傳遞    private Chengxuyuan c;    public CxyHandler(Chengxuyuan c) {        this.c = c;    }    /**     * 程式員介面的方法只要被調用就會通知到吃方法上     * @param proxy 代理對象      * @param method 告訴你 調用的方法 封裝對象     * @param args 參數     */    public Object invoke(Object proxy, Method method, Object[] args)            throws Throwable {        System.out.println("方法名稱:"+method.getName());        System.out.println("喝個咖啡,先把衣服穿上");        Object obj=method.invoke(c, args);//調用方法        System.out.println("衣服脫了,繼續喝咖啡");         return obj;    }}
package com.kaige123; import java.lang.reflect.Method;import java.lang.reflect.Proxy;/** * 測試類別 * @author 凱哥 * */public class Test {    public static void main(String[] args) {        //實作類別對象        ChengxuyuanImpl chengxuyuanImpl = new ChengxuyuanImpl();        //得到反射類        Class classs = chengxuyuanImpl.getClass();        //建立處理類 然後把實作類別對象傳遞        CxyHandler handler = new CxyHandler(chengxuyuanImpl);        //開始建立代理對象 然後把代理對象轉換成介面類型        Chengxuyuan chengxuyuan = (Chengxuyuan)                 Proxy.newProxyInstance(                        classs.getClassLoader(),                         classs.getInterfaces(),                        handler);        //調用方法  有如  >>>invoke(Object proxy, Method method, Object[] args)  >> xiedaima() >>調用完畢        chengxuyuan.xiedaima();    }}

結果:

方法名稱:xiedaima喝個咖啡,先把衣服穿上寫代碼...衣服脫了,繼續喝咖啡i

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.