cglib实现动态代理简单实现

package org.forever.xxxx.reflection;

import java.lang.reflect.Method;

import org.forever.xxxx.JpaDao;

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

public class CglibProxy {

	private MethodInterceptor methodInterceptor;

	public CglibProxy(MethodInterceptor methodInterceptor) {
		this.methodInterceptor = methodInterceptor;
	}

	public MethodInterceptor getMethodInterceptor() {
		return methodInterceptor;
	}

	public void setMethodInterceptor(MethodInterceptor methodInterceptor) {
		this.methodInterceptor = methodInterceptor;
	}

	public Object createProxy(Class<?> clazz) {
		Enhancer enhancer = new Enhancer();
		enhancer.setCallback(methodInterceptor);
		enhancer.setSuperclass(clazz);
		return enhancer.create();
	}

	public Object intercept(Object proxy, Method method, Object[] args,
			MethodProxy methodProxy) throws Throwable {
		System.out.println(method.getName());

		return methodProxy.invoke(proxy, args);
	}

	public static void main(String[] args) {
		CglibProxy cglibProxy = new CglibProxy(new DefaultMethodInterceptor());
		JpaDao jpaDao = (JpaDao) cglibProxy.createProxy(JpaDao.class);
		jpaDao.getTargetType();

	}

}

class DefaultMethodInterceptor implements MethodInterceptor {

	public Object intercept(Object proxy, Method method, Object[] args,
			MethodProxy methodProxy) throws Throwable {
		System.out.println(method.getName());
		return null;
	}

}

 

你可能感兴趣的:(.net)