import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class InvocationHandlerImpl implements InvocationHandler {
private Object targetObject;//要代理的目标对象
// 通过构造方法 传入要代理的目标对象
public InvocationHandlerImpl(Object targetObject) {
this.targetObject = targetObject;
}
// 创建代理对象
public Object createProxyInstance(){
Object proxyInstance = Proxy.newProxyInstance(targetObject.getClass().getClassLoader(),
targetObject.getClass().getInterfaces(),
this);
return proxyInstance;
}
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
long start = System.currentTimeMillis();
System.out.println(start);
//调用目标对象的方法
Object result = method.invoke(targetObject, args);
long end = System.currentTimeMillis();
System.out.println(end);
System.out.println("执行时间:"+(end-start)+"毫秒");
return result;
}
}
测试:
package com.bjpowernode.dao;
import junit.framework.TestCase;
public class ContactDaoTest extends TestCase {
public void testSave() {
ContactDao dao1 = new ContactDaoImpl();
//dao1.save();
ContactDao dao =(ContactDao) new InvocationHandlerImpl(dao1).createProxyInstance();
// dao.save();
System.out.println(dao.delete());
//dao.update();
}
}