标签:exception 依次 mac ack 返回 动态 模式 hand cat
public interface Machine { public void action(); }
public class Computer implements Machine { @Override public void action() { int num = 1+2; System.out.println("计算机计算结果为:"+num); } }
public class ComputerProxy extends Computer { public void action(){ long startTime = System.currentTimeMillis(); System.out.println("计算机开始计算"); super.action(); System.out.println("计算机停止执行"); long endTime=System.currentTimeMillis(); System.out.println("计算用时"+(endTime-startTime)+"毫秒"); } }
public class Client { public static void main(String[] args) { // TODO Auto-generated method stub Machine m = new ComputerProxy(); m.action(); } }
public class MachineTimerImp implements Machine{ public MachineTimerImp(Machine machine) { super(); this.machine = machine; } private Machine machine; public void action(){ long startTime = System.currentTimeMillis(); System.out.println("计算机开始计算"); machine.action(); System.out.println("计算机停止执行"); long endTime=System.currentTimeMillis(); System.out.println("计算用时"+(endTime-startTime)+"毫秒"); } }
public class MachineLogImp implements Machine{ private Machine machine; public MachineLogImp(Machine machine) { super(); this.machine = machine; } @Override public void action() { // TODO Auto-generated method stub System.out.println("日志开始"); machine.action(); System.out.println("日志记录结束"); } }
public class Client { public static void main(String[] args) { // TODO Auto-generated method stub Computer computer = new Computer(); Machine mt = new MachineTimerImp(computer); Machine mw = new MachineLogImp(mt); mw.action(); } }
public class Test { /** * jdk动态代理的测试类 * @throws SecurityException * @throws NoSuchMethodException */ public static void main(String[] args) throws NoSuchMethodException, SecurityException { Computer computer = new Computer(); InvocationHandler h = new TimeHandler(computer); Class<?> cls = computer.getClass(); System.out.println(cls.getInterfaces().getClass().getName()); Machine m= (Machine)Proxy.newProxyInstance(cls.getClassLoader(), cls.getInterfaces(),h); m.action(); } /** * loader 类加载器 * interfaces 实现接口 * h InvocationHandler */ }
public static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h)
这个方法传入
public class TimeHandler implements InvocationHandler { private Object target; public TimeHandler(Object target) { super(); this.target = target; } /** * proxy 被代理的对象 * method 被代理的对象的方法 * args 方法的参数 */ @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // TODO Auto-generated method stub long startTime = System.currentTimeMillis(); System.out.println("计算机开始计算"); method.invoke(target, args); System.out.println("计算机停止执行"); long endTime=System.currentTimeMillis(); System.out.println("计算用时"+(endTime-startTime)+"毫秒"); return null; } }
稍等。。。
标签:exception 依次 mac ack 返回 动态 模式 hand cat
原文地址:http://www.cnblogs.com/zipei/p/6110500.html