[color=red][b]注意被代理的类不能是final类型的。[/b][/color]
import java.lang.reflect.Method;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import org.junit.Test;
/**
* @author xxx
* @createDate 2014-5-31上午10:59:01
* @className CglibProxy.java
* @useFor cglib基于类的代理
*/
public class CglibProxy {
@Test
public void cglibProxy()
{
RealProxy realProxy = new RealProxy();
RealClass realClass = (RealClass)realProxy.getInstance(new RealClass()) ;
realClass.doSomething() ;
}
}
class RealClass
{
public void doSomething()
{
System.out.println("端午节");
}
};
/**
*
* @author lanweixing
* @createDate 2014-5-31上午11:01:42
* @className CglibProxy.java
* @useFor
*/
class RealProxy implements MethodInterceptor
{
/**
* 代理类
*/
private Object target;
public Object getInstance(Object target)
{
this.target = target;
Enhancer en = new Enhancer();
en.setSuperclass(target.getClass());
en.setCallback(this);
return en.create();
}
@Override
public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy)
throws Throwable
{
System.out.println("Before Advice");
Object result = proxy.invoke(target, args);
System.out.println("After Advice");
return result;
}
}