標籤:
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反射機制動態代理