CGLib实现动态代理
一 代码位置
https://gitee.com/cakin24/javatest
二 代码
1 CglibMeipo
package CGlib;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import java.lang.reflect.Method;
public class CglibMeipo implements MethodInterceptor {
public Object getInstance(Class<?> clazz) throws Exception{
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(clazz);
enhancer.setCallback(this);
return enhancer.create();
}
private void before(){
System.out.println("我是媒婆:我给你找对象,现在已经确认你的需求");
System.out.println("开始物色");
}
private void after(){
System.out.println("如果合适的话,就准备办事");
}
@Override
public Object intercept( Object o, Method method, Object[] objects, MethodProxy methodProxy ) throws Throwable {
before();
Object obj = methodProxy.invokeSuper(o,objects);
after();
return obj;
}
}
2 CGLibTest
package CGlib;
import net.sf.cglib.core.DebuggingClassWriter;
public class CGLibTest {
public static void main(String[] args){
try {
System.setProperty(DebuggingClassWriter.DEBUG_LOCATION_PROPERTY,"E://cglib_proxy_class/");
Customer obj = (Customer)new CglibMeipo().getInstance(Customer.class);
obj.findLove();
} catch (Exception e) {
e.printStackTrace();
}
}
}
3 Customer
package CGlib;
public class Customer{
public void findLove(){
System.out.println("高富帅");
System.out.println("身高180cm");
System.out.println("有6块腹肌");
}
}
三 测试
我是媒婆:我给你找对象,现在已经确认你的需求
开始物色
高富帅
身高180cm
有6块腹肌
如果合适的话,就准备办事
还没有评论,来说两句吧...