动态代理模式

 想实现动态代理就的用一个类实现(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类实现了此接口。

posted @ 2014-10-15 22:22  红色小宇宙  阅读(153)  评论(0编辑  收藏  举报