cglib-create分析
程序员文章站
2022-06-02 14:16:56
...
Enhancer主要用create创建类
public void testFixedValue() throws Exception {
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(SampleClass2.class);
enhancer.setCallback(new FixedValue() {
public Object loadObject() throws Exception {
return "Hello cglib!";
}
});
SampleClass2 proxy = (SampleClass2)enhancer.create();
Assertions.assertEquals("Hello cglib!", proxy.test((String)null));
}
EnhancerKey初始化:
//初始化父类的基本信息
private Source source;
private ClassLoader classLoader;
private String namePrefix;
//生成内部接口
private static final EnhancerKey KEY_FACTORY =
(EnhancerKey)KeyFactory.create(EnhancerKey.class, KeyFactory.HASH_ASM_TYPE, null);
Enchancer的create()调用父类AbstractClassGenerator的create方法
private Object createHelper() {
preValidate();
Object key = KEY_FACTORY.newInstance((superclass != null) ? superclass.getName() : null,
ReflectUtils.getNames(interfaces),
filter == ALL_ZERO ? null : new WeakCacheKey<CallbackFilter>(filter),
callbackTypes,
useFactory,
interceptDuringConstruction,
serialVersionUID);
this.currentKey = key;
Object result = super.create(key);
return result;
}
AbstractClassGenerator的create方法
protected Object create(Object key) {
try {
ClassLoader loader = getClassLoader();
Map<ClassLoader, ClassLoaderData> cache = CACHE;
ClassLoaderData data = cache.get(loader);
if (data == null) {
synchronized (AbstractClassGenerator.class) {
cache = CACHE;
data = cache.get(loader);
if (data == null) {
Map<ClassLoader, ClassLoaderData> newCache = new WeakHashMap<ClassLoader, ClassLoaderData>(cache);
data = new ClassLoaderData(loader);
newCache.put(loader, data);
CACHE = newCache;
}
}
}
this.key = key;
//获取类或方法的弱引用(这是特别关键的一步)
Object obj = data.get(this, getUseCache());
if (obj instanceof Class) {
//初始化类
return firstInstance((Class) obj);
}
//返回方法
return nextInstance(obj);
} catch (RuntimeException e) {
throw e;
} catch (Error e) {
throw e;
} catch (Exception e) {
throw new CodeGenerationException(e);
}
}
data.get(this, getUseCache())调用时序图:
上一篇: java ftp文件上传总结