根據我本身的的理解:微信
靜態代理是實現抽象接口,在代理匯中獲取代理對象的對象。須要一一去重寫抽象類中的方法。ide
動態代理使用的是反射,須要咱們傳入被代理類,並默認實現全部的目標方法,經過invoke中方法反射獲取menthod對象方法名稱便可實現。this
public class HuangNiuHandle implements InvocationHandler【1】 {
private Object proxyTarget;
public Object getProxyInstance(Object target) {
this.proxyTarget = target;
return Proxy.newProxyInstance【2】(proxyTarget.getClass().getClassLoader()【獲取代理類實例對象】, proxyTarget.getClass().getInterfaces(), this);
}
@Override【3】
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object methodObject = null;
System.out.println("line up");
methodObject = method.invoke(proxyTarget, args);
System.out.println("go home and sleep");
return methodObject;
}
}
當 咱們須要動態代理執行的僅是部分方法,那麼只須要進行方法名稱判斷便可。spa
public class HuangNiuHandle implements InvocationHandler { private Object proxyTarget; public Object getProxyInstance(Object target) { this.proxyTarget = target; return Proxy.newProxyInstance(proxyTarget.getClass().getClassLoader(), proxyTarget.getClass().getInterfaces(), this); } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Object methodObject = null; if ("lookConcert".equals(method.getName()) || "seeADoctor".equals(method.getName())) { System.out.println("line up"); // 調用目標方法 methodObject = method.invoke(proxyTarget, args); } else { // 不使用第一個proxy參數做爲參數,不然會形成死循環 methodObject = method.invoke(proxyTarget, args); } return methodObject; } }
參考微信公衆號:一個優秀的廢人一篇文章寫的,不能說懂了,可是得到了點東西,感謝!代理