動態代理模式

來源:互聯網
上載者:User

標籤:style   blog   http   color   io   ar   java   strong   sp   

 想實現動態代理就的用一個類實現(implements)一個InvocationHandler介面,此介面中有個方法

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

這個方法中接收有被代理類的方法method和方法的參數args,代理類。

  Proxy 類用來建立動態代理類和執行個體的靜態方法。有個方法將調用invoke()方法

可直接用 

static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h)
public static Object newProxyInstance(ClassLoader loader,  //我要代理的類的類載入   xx.getClass().getClassLoader()

Class<?>[] interfaces, //我要代理的類,讓我要實現的介面  xx.getClass().getInterfaces()
InvocationHandler h  
) throws IllegalArgumentException

代碼:

public class MyProxy implements InvocationHandler{
private Object iu; //我要代理的類對象 ,所有類型
public MyProxy(Object iu) { //傳入被代理的類執行個體
this.iu = iu;
}
public Object getProxy(){ //返回我(代理類)的執行個體 是一個介面類 要用介面接收
return Proxy.newProxyInstance(
this.iu.getClass().getClassLoader(), //我要代理的類的類載入
this.iu.getClass().getInterfaces(),//我要代理的類,讓我要實現的介面
this); //我要執行的代理類中的invoke()方法
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
System.out.println("開始代理");
method.invoke(this.iu, args); //調用被代理的類中的方法
return null;
}
}

test:

public static void main(String[] args) {
MyProxy m = new MyProxy(new UserImpl());
IUser u = (IUser) m.getProxy();

u.print(); //調用無參方法

u.xx("sdfsdfsdf");//調用有參方法
}

IUser 為介面其中有多個方法  UserImpl類實現了此介面。

動態代理模式

聯繫我們

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