}
import java.lang.reflect.Method;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
public class Proxy implements MethodInterceptor {
private Class target=null;//要代理的类型
//构造函数,传入要代理类的 类型
public Proxy(Class target){
this.target=target;
}
//获取代理类
public Object getDao( ){
Enhancer enhancer=new Enhancer();
enhancer.setSuperclass(target);
enhancer.setCallback(this);
return enhancer.create();
}
/**
* 拦截方法
* @param obj :被拦截类的一个实例
* @param method :被拦截类现在执行的方法
* @param args :被拦截类现在执行的方法 所要传入的参数
* @return 被拦截类现在执行的方法的返回值
*/
public Object intercept(Object obj, Method method, Object[] args,
MethodProxy methodProxy) throws Throwable {
Object returnObj=null;
System.out.println("-----------------代理"+method.getName()+ "方法开始");
returnObj=methodProxy.invokeSuper(obj, args);
System.out.println("-----------------代理"+method.getName()+ "方法结束/n");
return returnObj;
}
}
import net.sf.cglib.core.DebuggingClassWriter;
public class Client {
public static void main(String[] args) {
//System.setProperty(DebuggingClassWriter.DEBUG_LOCATION_PROPERTY, "c://");
Proxy proxy=new Proxy(Dao.class);
Dao dao=(Dao)proxy.getDao();
dao.select(1);
dao.insert(2);
dao.update(3);
}
}
运行结果
-----------------代理select方法开始
DAO--->select
-----------------代理select方法结束
-----------------代理insert方法开始
DAO--->insert---->2
-----------------代理insert方法结束
-----------------代理update方法开始
DAO--->update---->3
-----------------代理update方法结束