標籤: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類實現了此介面。
動態代理模式