package com.gewb.proxy; import java.util.Random; public class Car implements Moveable{ @Override public void move() { try { System.out.println("汽车行驶中。。。"); Thread.sleep(new Random().nextInt(1000)); } catch (InterruptedException e) { e.printStackTrace(); } } } package com.gewb.proxy; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; 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 { long starttime = System.currentTimeMillis(); System.out.println("汽车开始行驶"); method.invoke(target); long endtime = System.currentTimeMillis(); System.out.println("汽车行驶结束"); System.out.println("用时" + (endtime - starttime) + "毫秒"); return null; } } package com.gewb.proxy; public class LogHandler implements Moveable { private Moveable m; public LogHandler(Moveable m) { super(); this.m = m; } @Override public void move() { System.out.println("日志记录开始"); m.move(); System.out.println("日志记录结束"); } } package com.gewb.proxy; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Proxy; public class Main { public static void main(String[] args) { Car car = new Car(); LogHandler h = new LogHandler(car); InvocationHandler handler = new TimeHandler(h); Moveable instance = (Moveable) Proxy.newProxyInstance(car.getClass().getClassLoader(), car.getClass().getInterfaces(), handler); instance.move();
