JDK Proxy 小試

demo

在本 demo 中我們將創(chuàng)建一個 door 接口,實(shí)現(xiàn)對接口中所有方法的代理。
door.java

public interface Door {

    void enter();

    void out();

}

HomeDoorImpl.java

public class HomeDoorImpl implements Door{

    @Override
    public void enter() {
        System.out.println("enter the home door");
    }

    @Override
    public void out() {
        System.out.println("out the home door");
    }
}

main and proxy

public class Proxy implements InvocationHandler {

    private Object target;

    public Proxy(Object target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("start proxy");
        Object res = method.invoke(target, args);
        System.out.println("end proxy");
        return res;
    }


    public static void main(String[] args) {
        Door door;
        Proxy proxy = new Proxy(door = new HomeDoorImpl());
        door = (Door) java.lang.reflect.Proxy.newProxyInstance(door.getClass().getClassLoader(),
                door.getClass().getInterfaces(), proxy);
        door.enter();
        door.out();
    }

}

運(yùn)行

輸出

start proxy
enter the home door
end proxy
start proxy
out the home door
end proxy

僅代理某個方法

可以看到我們將 Door 接口中的所有方法都代理躲查,但在實(shí)際業(yè)務(wù)中可能僅代理某些方法上陕。
接下來做一些小改動來支持這個功能。我們決定通過在方法上添加注解決定是否真正代理(PS:本質(zhì)上實(shí)現(xiàn)類的所有方法都會被代理)
NeedProxy.java

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface NeedProxy {}

HomeDoorImpl.javaenter 方法添加注解

public class HomeDoorImpl implements Door{

    @NeedProxy
    @Override
    public void enter() {
        System.out.println("enter the home door");
    }

    @Override
    public void out() {
        System.out.println("out the home door");
    }
}

Proxy.java 使用 Map 集合保存了需要代理的方法球匕,在 invoke function 時判斷是否執(zhí)行代理邏輯嘹悼。

public class Proxy implements InvocationHandler {

    private HashMap<String, Object> proxyMethods = new HashMap<>();
    private Object target;

    public Proxy(Object target) {
        this.target = target;
        Method[] methods = target.getClass().getMethods();
        for (Method method : methods) {
            Annotation[] annotations = method.getAnnotations();
            for (Annotation annotation : annotations) {
                if (annotation.annotationType().equals(NeedProxy.class)) {
                    proxyMethods.put(method.getName(), Void.TYPE);
                    break;
                }
            }
        }
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if (proxyMethods.containsKey(method.getName())) {
            return invoke0(proxy, method, args);
        }
        return method.invoke(target, args);
    }

    private Object invoke0(Object proxy, Method method, Object[] args) throws InvocationTargetException, IllegalAccessException {
        System.out.println("start proxy");
        Object res = method.invoke(target, args);
        System.out.println("end proxy");
        return res;
    }


    public static void main(String[] args) {
        Door door;
        Proxy proxy = new Proxy(door = new HomeDoorImpl());
        door = (Door) java.lang.reflect.Proxy.newProxyInstance(door.getClass().getClassLoader(),
                door.getClass().getInterfaces(), proxy);
        door.enter();
        door.out();
    }

}

輸出

------start proxy-----
enter the home door
------end proxy-------
out the home door

實(shí)現(xiàn)一個 before-after

真實(shí)業(yè)務(wù)上不可能所有方法都是一樣的代理邏輯(PS:logger 是可以使用同一個邏輯的)如何模擬實(shí)現(xiàn)一個類似真實(shí)業(yè)務(wù)的 before-after叛甫,我們決定在 NeedProxyProxy 上下工夫。
BeforeAfter.java 定義一個 before-after 接口杨伙,這里可以根據(jù)不同的業(yè)務(wù)邏輯實(shí)現(xiàn),after 方法頁可以包裝以下 result 再吐出去萌腿。

public interface BeforeAfter{
    void before(Object[] args);
    void after(Object result);
}

NeedProxy.java

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface NeedProxy {
    Class<? extends BeforeAfter> beforeAfter();
}

HomeDoorImpl.java

public class HomeDoorImpl implements Door{

    @NeedProxy(beforeAfter = HomeDoorEnterBeforeAfter.class)
    @Override
    public void enter() {
        System.out.println("enter the home door");
    }

    @Override
    public void out() {
        System.out.println("out the home door");
    }
}

HomeDoorEnterBeforeAfter.java

public class HomeDoorEnterBeforeAfter implements BeforeAfter {

    @Override
    public void before(Object[] args) {
        System.out.println("打開室外燈");
    }

    @Override
    public void after(Object result) {
        System.out.println("關(guān)閉室外燈");
    }
}

Door.java 目前代理邏輯中還沒有一個 HomeDoorEnterBeforeAfter 實(shí)例限匣,可能 BeforeAfter 構(gòu)造方法需要依賴。下方采用反射構(gòu)造實(shí)例。

public class Proxy implements InvocationHandler {

    private HashMap<String, BeforeAfter> proxyMethods = new HashMap<>();
    private Object target;

    public Proxy(Object target) throws IllegalAccessException, InstantiationException {
        this.target = target;
        Method[] methods = target.getClass().getMethods();
        for (Method method : methods) {
            Annotation[] annotations = method.getAnnotations();
            for (Annotation annotation : annotations) {
                if (annotation.annotationType().equals(NeedProxy.class)) {
                    NeedProxy needProxy = (NeedProxy) annotation;
                    proxyMethods.put(method.getName(), needProxy.beforeAfter().newInstance());
                    break;
                }
            }
        }
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        BeforeAfter beforeAfter;
        if ((beforeAfter = proxyMethods.get(method.getName())) != null) {
            return invoke0(beforeAfter, proxy, method, args);
        }
        return method.invoke(target, args);
    }

    private Object invoke0(BeforeAfter beforeAfter, Object proxy, Method method, Object[] args) throws InvocationTargetException, IllegalAccessException {
        beforeAfter.before(args);
        Object res = method.invoke(target, args);
        beforeAfter.after(res);
        return res;
    }


    public static void main(String[] args) throws InstantiationException, IllegalAccessException {
        Door door;
        Proxy proxy = new Proxy(door = new HomeDoorImpl());
        door = (Door) java.lang.reflect.Proxy.newProxyInstance(door.getClass().getClassLoader(),
                door.getClass().getInterfaces(), proxy);
        door.enter();
        door.out();
    }

}

輸出

打開室外燈
enter the home door
關(guān)閉室外燈
out the home door

小結(jié)

可以看到 JDK 的動態(tài)代理實(shí)現(xiàn)代理顆粒度較為粗糙米死,并且需要入侵所有方法锌历,性能上可能有所下降。讀者如果對 Proxy 有興趣的話峦筒,可以進(jìn)一步了解 cglib 是如何實(shí)現(xiàn)代理的究西。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市物喷,隨后出現(xiàn)的幾起案子卤材,更是在濱河造成了極大的恐慌,老刑警劉巖峦失,帶你破解...
    沈念sama閱讀 219,270評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件扇丛,死亡現(xiàn)場離奇詭異,居然都是意外死亡尉辑,警方通過查閱死者的電腦和手機(jī)帆精,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,489評論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來隧魄,“玉大人卓练,你說我怎么就攤上這事」鹤模” “怎么了襟企?”我有些...
    開封第一講書人閱讀 165,630評論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長闸溃。 經(jīng)常有香客問我整吆,道長,這世上最難降的妖魔是什么辉川? 我笑而不...
    開封第一講書人閱讀 58,906評論 1 295
  • 正文 為了忘掉前任表蝙,我火速辦了婚禮,結(jié)果婚禮上乓旗,老公的妹妹穿的比我還像新娘府蛇。我一直安慰自己,他們只是感情好屿愚,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,928評論 6 392
  • 文/花漫 我一把揭開白布汇跨。 她就那樣靜靜地躺著,像睡著了一般妆距。 火紅的嫁衣襯著肌膚如雪穷遂。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,718評論 1 305
  • 那天娱据,我揣著相機(jī)與錄音蚪黑,去河邊找鬼。 笑死,一個胖子當(dāng)著我的面吹牛忌穿,可吹牛的內(nèi)容都是我干的抒寂。 我是一名探鬼主播,決...
    沈念sama閱讀 40,442評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼掠剑,長吁一口氣:“原來是場噩夢啊……” “哼屈芜!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起朴译,我...
    開封第一講書人閱讀 39,345評論 0 276
  • 序言:老撾萬榮一對情侶失蹤井佑,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后动分,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體毅糟,經(jīng)...
    沈念sama閱讀 45,802評論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,984評論 3 337
  • 正文 我和宋清朗相戀三年澜公,在試婚紗的時候發(fā)現(xiàn)自己被綠了姆另。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,117評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡坟乾,死狀恐怖迹辐,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情甚侣,我是刑警寧澤明吩,帶...
    沈念sama閱讀 35,810評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站殷费,受9級特大地震影響印荔,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜详羡,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,462評論 3 331
  • 文/蒙蒙 一仍律、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧实柠,春花似錦水泉、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,011評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至蟹漓,卻和暖如春炕横,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背葡粒。 一陣腳步聲響...
    開封第一講書人閱讀 33,139評論 1 272
  • 我被黑心中介騙來泰國打工看锉, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留姿锭,地道東北人塔鳍。 一個月前我還...
    沈念sama閱讀 48,377評論 3 373
  • 正文 我出身青樓伯铣,卻偏偏與公主長得像,于是被迫代替她去往敵國和親轮纫。 傳聞我的和親對象是個殘疾皇子腔寡,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,060評論 2 355