读书人

JAVA的动态署理

发布时间: 2012-10-28 09:54:44 作者: rapoo

JAVA的动态代理
java的动态代理主要实现了InvocationHandler接口的代理类,并且重写了此接口中的invoke方法。然后在调用类中使用newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h)来调用。下面通过一个例子来说明动态代理。
Cat接口

public interface Cat {public void eat(String food);}

两个实现类Cat1,Cat2
public class Cat1 implements Cat {public void eat(String food) {System.out.println("cat1 is eating "+food);}}public class Cat2 implements Cat {public void eat(String food) {System.out.println("cat2 is eating "+food);}}

代理类CatInvocationHandler
public class CatInvocationHandler implements InvocationHandler {Object obj;public CatInvocationHandler(Object obj) {this.obj = obj;}public Object invoke(Object proxy, Method method, Object[] args)throws Throwable {return method.invoke(obj, args);}}

客户端类:Client,通过代理类调用两个被代理类
public class Client {public static void main(String[] args) {CatInvocationHandler h = new CatInvocationHandler(new Cat1());//注意参数中使用的是被代理类Cat cat1 = (Cat)Proxy.newProxyInstance(Cat1.class.getClassLoader(), Cat1.class.getInterfaces(), h);cat1.eat("meat");h = new CatInvocationHandler(new Cat2());Cat cat2 =(Cat)Proxy.newProxyInstance(Cat1.class.getClassLoader(), Cat1.class.getInterfaces(), h);cat2.eat("fish");}}

读书人网 >软件架构设计

热点推荐