使用cglib创建代理类

import java.lang.reflect.Method;

import com.dao.impl.PersonDaoImpl;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

//当代理对象没有实现接口,我们就可以 使用CGLIB生成代理 ,需要我们使用 cglib-nodep-2.1_3.jar
public class CGlibProxyFactory implements MethodInterceptor {
	private Object targetObject;// 代理的目标对象

	public Object createProxyInstance(Object targetObject) {
		this.targetObject = targetObject;
		Enhancer enhancer = new Enhancer();// 该类用于生成代理对象
		enhancer.setSuperclass(this.targetObject.getClass());// 设置父类
		enhancer.setCallback(this);// 设置回调用对象为本身
		return enhancer.create();
	}

	public Object intercept(Object proxy, Method method, Object[] args,
			MethodProxy methodProxy) throws Throwable {
		PersonDaoImpl bean = (PersonDaoImpl) this.targetObject;  
        Object result = null;   
        if(bean.getUser()!=null){  
            try {  
                result = methodProxy.invoke(this.targetObject, args);;  
            } catch (RuntimeException e) {  
            } 
        }  
		return result;
	}
}

你可能感兴趣的:(java,DAO,.net,bean)