//这个接口定义一个可以移动的方法
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;
}
@Override
public 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();
}
}