动态代理的简单实现
//这个接口定义一个可以移动的方法public interface Moveable {void move();}//Car类实现了Moveable接口public class Car implements Moveable {public void move() {System.out.println("Car moving!");try {Thread.sleep(new Random().nextInt(10000));} catch (InterruptedException e) {e.printStackTrace();}}}//定义一个记录方法运行时间的操作类import java.lang.reflect.InvocationHandler;import java.lang.reflect.Method;public class TimeHandler implements InvocationHandler {Moveable m;public TimeHandler(Moveable m) {super();this.m = m;}@Overridepublic Object invoke(Object proxy, Method method, Object[] args)throws Throwable {long start = System.currentTimeMillis();method.invoke(m, null);long end = System.currentTimeMillis();System.out.println("time:" + (end - start));return null;}}//测试代理import java.lang.reflect.InvocationHandler;import java.lang.reflect.Proxy;public class Test {public static void main(String[] args) {Car c = new Car();InvocationHandler h = new TimeHandler(c);Moveable m = (Moveable) Proxy.newProxyInstance(Test.class.getClassLoader(), new Class[] { Moveable.class }, h);m.move();}}
?