1、定义TimeHandler,并实现InvocationHandler接口
public class TimeHandler implements InvocationHandler {
private Object target;//定义目标类
public TimeHandler(Object target) {
super();
this.target = target;
}
/*
*
*/
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
long starttime=System.currentTimeMillis();
System.out.println("汽车开始行驶。。");
System.out.println("日志开始。。");
method.invoke(target);
System.out.println("日志结束。。");
long endtime=System.currentTimeMillis();
System.out.println("汽车行驶结束。。"+"行驶时间为:"+(endtime-starttime)+"毫秒");
return null;
}
}
2、定义要代理的类
1>定义接口
public interface Moveable {
void move();
}
2>类
public class Car implements Moveable {
@Override
public void move() {
//实现开车
try {
System.out.println("汽车正在行驶。。");
Thread.sleep(new Random().nextInt(1000));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
3、对目标类car进行jdk动态代理
//jdk动态代理
@Test
public void test06() {
Car car=new Car();
Class<?> cls=car.getClass();
InvocationHandler h=new TimeHandler(car);
Moveable m=(Moveable) Proxy.newProxyInstance(cls.getClassLoader(), cls.getInterfaces(), h);
m.move();
}
4、测试结果: