实现JDK动态代理的时间和日志
时间代理:
package com.proxy.jdkproxy;
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 方法的参数
* 返回值:Object方法的返回值
*/
@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);
long endtime=System.currentTimeMillis();
System.out.println("汽车结束行驶了,一个行驶了:"+(endtime-starttime)+"毫秒");
return null;
}
}
日志代理:
package com.proxy.jdkproxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class LogHandler implements InvocationHandler {
private Object object;
public LogHandler(Object object) {
super();
this.object = object;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// TODO Auto-generated method stub
System.out.println("日志开始了");
method.invoke(object);
System.out.println("日志结束了");
return null;
}
}
主函数:
package com.proxy.jdkproxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import com.proxy.statics.Car;
import com.proxy.statics.Moveable;
public class JdkMain {
public static void main(String[] args) {
// TODO Auto-generated method stub
Car car = new Car();
InvocationHandler ht=new TimeHandler(car);
InvocationHandler hl=new LogHandler(car);
//得到Car的class
Class<?> cls = Car.class;
/*采用动态代理生成动态代理类
* loader 被代理类的类加载器
* interfaces 实现的接口
* h 事件处理器,InvocationHandler
*/
Moveable mt =(Moveable) Proxy.newProxyInstance(cls.getClassLoader(),
cls.getInterfaces(), ht);
Moveable ml =(Moveable) Proxy.newProxyInstance(cls.getClassLoader(),
cls.getInterfaces(), hl);
mt.move();
ml.move();
}
}
代码的执行结果:
稍微有点遗憾的是“汽车正在运行中...”这句话显示了两遍,不知道有没有什么方法能只运行一次的。
欢迎大家留言讨论
热门评论
public static void main(String[] args) {
// TODO Auto-generated method stub
Car car = new Car();
InvocationHandler handler = new TimeHandler(car);
Class<?> c = car.getClass();
Movable m1 = (Movable) Proxy.newProxyInstance(c.getClassLoader(), c.getInterfaces(), handler);
InvocationHandler handler2 = new LogHandler(m1);
Class<?> c2 = m1.getClass();
Movable m2 = (Movable) Proxy.newProxyInstance(c2.getClassLoader(), c2.getInterfaces(), handler2);
m2.move();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Car car = new Car();
InvocationHandler handler = new TimeHandler(car);
Class<?> c = car.getClass();
Movable m1 = (Movable) Proxy.newProxyInstance(c.getClassLoader(), c.getInterfaces(), handler);
InvocationHandler handler2 = new LogHandler(m1);
Class<?> c2 = m1.getClass();
Movable m2 = (Movable) Proxy.newProxyInstance(c2.getClassLoader(), c2.getInterfaces(), handler2);
m2.move();
}
你成功的骗我看了一遍