由于种种原因,最近在对以前用过的技术进行回顾梳理,在这期间发现hibernate与spring在很大程度上用到动态代理,象hibernate里面的延迟加载,加载的是代理的id,当get()非id的时候,才会实例具体的对象。spring的核心之一aop,也是通过动态代理实现的。下面先看一个简单的动态代理demo。
被代理类:
public class MyClass {
public void method() {
System.out.println("MyClass.method()");
}
}
代理类:
import java.lang.reflect.Method;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodProxy;
import net.sf.cglib.proxy.MethodInterceptor;
public class Main {
public static void main(String[] args) {
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(MyClass.class);
enhancer.setCallback( new MethodInterceptorImpl() );
MyClass my = (MyClass)enhancer.create();
my.method();
}
private static class MethodInterceptorImpl implements MethodInterceptor {
public Object intercept(Object obj,
Method method,
Object[] args,
MethodProxy proxy) throws Throwable {
System.out.println(method);
proxy.invokeSuper(obj, args);
return null;
}
}
}
类似Enhancer可以增加CallbackFilter
另外一种实现与spring类相似:
public interface MyInterfaceA {
public void methodA();
}
public interface MyInterfaceB {
public void methodB();
}
public class MyInterfaceAImpl implements MyInterfaceA {
public void methodA() {
System.out.println("MyInterfaceAImpl.methodA()");
}
}
public class MyInterfaceBImpl implements MyInterfaceB {
public void methodB() {
System.out.println("MyInterfaceBImpl.methodB()");
}
}
import net.sf.cglib.proxy.Mixin;
public class Main {
public static void main(String[] args) {
Class[] interfaces =
new Class[] { MyInterfaceA.class, MyInterfaceB.class };
Object[] delegates =
new Object[] { new MyInterfaceAImpl(), new MyInterfaceBImpl() };
Object obj = Mixin.create(interfaces, delegates);
MyInterfaceA myA = (MyInterfaceA)obj;
myA.methodA();
MyInterfaceB myB = (MyInterfaceB)obj;
myB.methodB();
}
}