package com.gewb.proxy;
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 CglibProxy implements MethodInterceptor {
// 用于产生代理类
private Enhancer enhancer = new Enhancer();
public Object getProxy(Class clazz) {
// 设置产生代理类的子类
enhancer.setSuperclass(clazz);
enhancer.setCallback(this);
return enhancer.create();
}
/**
* 拦截方法调用
* obj 目标实例
* method 目标方法
* args 目标方法参数
* proxy 代理类实例
*/
@Override
public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
System.out.println("火车开动了");
proxy.invokeSuper(obj, args);
System.out.println("火车到站了");
return null;
}
}
package com.gewb.proxy;
public class Train {
public void move() {
System.out.println("火车行驶中...");
}
}
package com.gewb.proxy;
public class Main {
public static void main(String[] args) {
CglibProxy proxy = new CglibProxy();
Train train = (Train) proxy.getProxy(Train.class);
train.move();
}
}