package com.bingo.frame.oop.cls;
import java.lang.reflect.Method;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
/**
* 类加载时, 加如Metaspace内存空间比较小, 可能会导致OOM(Out Of Memory Error-内存溢出)
* @author bingo
*/
//-XX:MetaspaceSize=5m -XX:MaxMetaspaceSize=10m
//-XX:+PrintFlagsInitial
public class TestClassLoader08 {
public static void main(String[] args) {
//借助字节码增强技术创建Object类的子类
//借助CGLIB库中的API为Object类创建子类
while (true) {
//构建增强对象,通过此对象为目标类创建子类对象
Enhancer enhancer = new Enhancer();
//设置父类对象类型
enhancer.setSuperclass(Object.class);
//设置不使用缓存
enhancer.setUseCache(false);//默认true, 使用缓存中对象
//设置回调对象
enhancer.setCallback(new MethodInterceptor() {//调用目标方法时拦截,可以进行一些操作
//调用子类增强对象(代理对象)方法时自动执行
public Object intercept(
Object obj, //增强对象(目标对象的子类-代理)
Method method, //目标方法对象
Object[] args, //目标方法参数
MethodProxy proxy//用来调用父类的代理
) throws Throwable {
//执行目标对象方法
long start = System.currentTimeMillis();
Object result = proxy.invokeSuper(obj, args);
long end = System.currentTimeMillis();
System.out.println("excute time: "+(end-start));
return result;
}
});
//为Object类创建子类对象
Object child = enhancer.create();
System.out.println("toString: "+child.toString());
}
}
}