萌汉子
2015-11-03 15:49
如何在jdk动态代理的中实现多个代理?(时间代理,日志代理)
//jdk动态代理测试类 public static void main(String []args) { Car car=new Car(); InvocationHandler h1=new TimeHandler(car); Class<?> time=car.getClass(); /** * loader 类加载器 * interface 实现接口 * h InvocationHandler */ //返回代理类的一个实例,返回后的代理类可以当作被代理类使用 Moveable t=(Moveable)Proxy.newProxyInstance(time.getClassLoader(), time.getInterfaces(),h1);// t.move(); InvocationHandler h2=new LogHandler(t); Class<?> log=t.getClass(); Moveable l=(Moveable)Proxy.newProxyInstance(log.getClassLoader(), log.getInterfaces(),h2); l.move();
Car car = new Car();
InvocationHandler time = new TimeHandler(car);
Class<?> cls = car.getClass();
Moveable m = (Moveable) Proxy.newProxyInstance(cls.getClassLoader(), cls.getInterfaces(), time);
m.move();
System.out.println("****************************");
// 获得Car的TimeHandler代理类后,继续获得代理类的代理,即对代理类进行再代理
InvocationHandler log = new LogHandler(m);
Class<?> proxyCls = m.getClass();
Moveable l = (Moveable) Proxy.newProxyInstance(proxyCls.getClassLoader(), proxyCls.getInterfaces(), log);
l.move();
如何在jdk动态代理的中实现多个代理?(时间代理,日志代理)
模式的秘密---代理模式
54906 学习 · 134 问题
相似问题