java有兩種動態代理
一:JDK動態代理:Proxy
二:CGLIB動態代理:Enhancer
動態代理的實質是利用字節碼工具,生成新的代理類,替換原始的類。
我們首先看JDK代理模式
創建代理對象需要入參 ClassLoader,被代理的對象的接口數組,一個新的InvocationHandler。
看demo
public class ProxyFactoryTest {
public static Object getProxyObj(Object targetObj){
MyInvocationHandler invocation = new MyInvocationHandler(targetObj);
return Proxy.newProxyInstance(targetObj.getClass().getInterfaces()[0].getClassLoader(),new Class[]{ targetObj.getClass().getInterfaces()[0]}, invocation);
}
}
public class MyInvocationHandler implements InvocationHandler {
private Object originBean;
public MyInvocationHandler(Object originBean) {
this.originBean = originBean;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
beforeProxy();
Object result = method.invoke(originBean, args);
afterProxy();
return result;
}
private void afterProxy() {
System.out.println("after proxy");
}
private void beforeProxy() {
System.out.println("before proxy");
}
}
public interface SelfInterface {
String getName();
}
public class SelfBean implements SelfInterface {
@Override
public String getName() {
System.out.println("selfBean");
return "this is SelfBean";
}
}
在我們調用ProxyFactoryTest的getProxyObj方法的時候,我們生成了一個新的class
新的Class繼承了Proxy,實現了實際SelfBean的接口。那在執行getName()方法是,字節碼已經變成了執行InvocationHandler的invoke()方法,這個就是我們在新建代理對象時,傳入的自定義的InvocationHandler;
上面就是JDK的動態代理。