一、用前准备
二、用例:
1、创建一个类的动态代理,并同时为其实现指定的接口,即动态实现接口
下面例子动态的为App类实现了Runnable接口
import org.junit.Test;
public class AppTest {
@Test
public void testCglib(){
CglibProxy proxy = new CglibProxy();
try {
Runnable run = (Runnable) proxy.getBean(Class.forName("com.xxx.xxx.App"), Runnable.class);
run.run();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
import java.lang.reflect.Method;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
/**
* 使用cglib实现的动态代理
*
* @author yaoxing
*/
public class CglibProxy implements MethodInterceptor {
private Enhancer enhancer = new Enhancer();
/**
* 动态创建一个类的代理,同时为其实现指定的接口
*
* @param src
* 要生成代理的类
* @param interfaces
* 要为代理类实现的接口
* @return 已实现了接口的代理类对象
*/
public Object getBean(Class src, Class...interfaces) {
enhancer.setSuperclass(src);
enhancer.setCallback(this);
enhancer.setInterfaces(interfaces);
return enhancer.create();
}
public Object intercept(Object object, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
System.out.println("提前执行");
Object result = methodProxy.invokeSuper(object, args);
System.out.println("延后执行");
return result;
}
}
public class App {
/**
* 要动态为类实现接口,就要提前实现好接口的方法
*/
public void run() {
System.out.println("run method is called");
}
}