本帖最后由 旭辉lin 于 2014-9-8 21:08 编辑
- package bao3;
- import java.lang.reflect.Method;
- import java.util.TreeSet;
- import net.sf.cglib.proxy.Enhancer;
- import net.sf.cglib.proxy.MethodInterceptor;
- import net.sf.cglib.proxy.MethodProxy;
- public class CglibDemo {
- public static void main(String[] args) {
- CGlibProxyFactory factory = new CGlibProxyFactory();
- TreeSet ts = (TreeSet) factory.createProxyInstance(new TreeSet());
- System.out.println(ts.getClass().getName());
- }
- }
- class CGlibProxyFactory implements MethodInterceptor {
- private Object targetObject;
- public Object createProxyInstance(Object targetObject) {
- this.targetObject = targetObject; // 传入用户类
- Enhancer enhancer = new Enhancer(); // Enhancer是cglib的核心类
- // 将用户类设为 Enhancer对象的superclass属性,,即设为 Enhancer对象的父类
- enhancer.setSuperclass(this.targetObject.getClass());
- // 设 Enhancer对象的Callbacks属性,要求必须是Callback接口类型
- enhancer.setCallback(this);
- return enhancer.create(); // 生成代理对象
- }
- @Override
- public Object intercept(Object arg0, Method arg1, Object[] arg2,
- MethodProxy arg3) throws Throwable {
- return arg1.invoke(targetObject, null);
- // return null;
- }
- }
复制代码
|