Cglib动态代理实例

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 Test{

	public static void main(String[] args) {
		MyProxy proxy = new MyProxy();
		Biz biz = (Biz)proxy.getProxy(Biz.class);
		biz.biz();
	}
}

class MyProxy implements MethodInterceptor {

	private Enhancer enhancer = new Enhancer();
	
	public Object getProxy(Class clazz) {
		enhancer.setSuperclass(clazz);
		enhancer.setCallback(this);
		return enhancer.create();
	}
	
	public Object intercept(Object obj, Method method, Object[] args,
			MethodProxy proxy) throws Throwable {
		System.out.println("Before......");
		Object result = proxy.invokeSuper(obj, args);
		System.out.println("After......");
		return result;
	}
	
}

class Biz {
	public void biz() {
		System.out.println("biz()......");
	}
}

你可能感兴趣的:(Cglib动态代理实例)