cglib:cglib is the initial of the Code Generation Library. it can manipulate the byte codes freely,it depends on asm opensource framework,Asm is also the bytecodes framework,but it is harder to use than the cglib.
hibernate uses the cglib to come to the two main functions :
1 generate the po(persistent object) at the runtime,it means you can use cglib to generate proxies for persistent classes
2 implement the lazy function at the runtime ,lazy loading is divided in to three values:true false ,values, we much use the lazy loading carefully
spring uses the cglib to implement the aop
for example:
package asm;
import java.lang.reflect.Method;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
public class CglibTest {
public static void main(String[] args) {
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(MyClass.class);
enhancer.setCallback(new MethodInterceptorImpl());
MyClass my = (MyClass) enhancer.create();
my.print();
}
private static class MethodInterceptorImpl implements MethodInterceptor {
public Object intercept(Object obj, Method method, Object[] args,
MethodProxy proxy) throws Throwable {
// log something
System.out.println(method + " intercepted!");
proxy.invokeSuper(obj, args);
return null;
}
}
}
package asm;
public class MyClass {
public void print() {
System.out.println("I'm in MyClass.print!");
}
}
hibernate uses the cglib to come to the two main functions :
1 generate the po(persistent object) at the runtime,it means you can use cglib to generate proxies for persistent classes
2 implement the lazy function at the runtime ,lazy loading is divided in to three values:true false ,values, we much use the lazy loading carefully
spring uses the cglib to implement the aop
for example:
package asm;
import java.lang.reflect.Method;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
public class CglibTest {
public static void main(String[] args) {
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(MyClass.class);
enhancer.setCallback(new MethodInterceptorImpl());
MyClass my = (MyClass) enhancer.create();
my.print();
}
private static class MethodInterceptorImpl implements MethodInterceptor {
public Object intercept(Object obj, Method method, Object[] args,
MethodProxy proxy) throws Throwable {
// log something
System.out.println(method + " intercepted!");
proxy.invokeSuper(obj, args);
return null;
}
}
}
package asm;
public class MyClass {
public void print() {
System.out.println("I'm in MyClass.print!");
}
}
本文介绍了cglib作为代码生成库的基本概念及其依赖的ASM框架。重点讲述了cglib在Hibernate中的两大应用:运行时生成持久化对象代理以及实现懒加载功能。此外,还通过Spring使用cglib实现AOP的例子展示了cglib的具体使用方法。
4932

被折叠的 条评论
为什么被折叠?



