Talk is cheap. Show me the code
第一步:编写一个类,用于被CGLIB增强。
package com.xxx.hyl.cglib;
public class BaseBean {
public void say() {
System.out.println("this is son");
}
}
第一种方式查看CGLIB增强后的Class。
package com.xxx.hyl.cglib;
import net.sf.cglib.core.DebuggingClassWriter;
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 CglibDemo {
public static void main(String[] args) {
// 指定 CGLIB 将动态生成的代理类保存至指定的磁盘路径下
System.setProperty(DebuggingClassWriter.DEBUG_LOCATION_PROPERTY, "D:\\cglib");
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(BaseBean.class);
enhancer.setCallback(new CustomizedMethodInterceptor());
BaseBean baseBean = (BaseBean) enhancer.create();
baseBean.say();
}
static class CustomizedMethodInterceptor implements MethodInterceptor {
@Override
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy)
throws Throwable {
System.out.println("invoke " + method.getName() + " before ! ");
Object result = methodProxy.invokeSuper(o, objects);
System.out.println("invoke " + method.getName() + " after ! ");
return result;
}
}
}
第二种方式,借助于Java的HSDB。
1.通过cmd找到当前Java进程PID。
2.在JDK的lib目录下,找到sa-jdi.jar执行:java -classpath sa-jdi.jar “sun.jvm.hotspot.HSDB”
3.点击File->Attach to hotspot process
4.在HSDB输入对应进程后,点击Tools->Class Browser然后输入要查找的类。
5.点击就会创建.class文件,路径为sa-jdl.jar所在的路径
6.可以把这个.class文件拖到Idea中进行查看。