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!");
}
}