反射注解與動態(tài)代理綜合使用

睡覺之前悦昵,為了更好地入眠,讓我們來學(xué)習(xí)下反射+注解+動態(tài)代理的綜合使用姿勢。在上篇文章中我們簡單的聊了下動態(tài)代理函匕,今天我們結(jié)合反射和注解來一起看下。首先會先簡單看下反射和注解蚪黑,動態(tài)代理請參考上篇博客:http://www.reibang.com/p/b00ef12d53cc
然后會綜合通過一個Android的小栗子進行實戰(zhàn)盅惜。

1.反射

先儲備下理論知識,具體的應(yīng)用可以看后面的栗子忌穿。
利用Java的反射可以在運行狀態(tài)下把一個class內(nèi)部的成員方法/字段和構(gòu)造函數(shù)全部獲得抒寂,甚至可以進行實例化,調(diào)用內(nèi)部方法掠剑。是不是很厲害的樣子屈芜?
比較常用的方法:

getDeclaredFields(): 可以獲得class的成員變量
getDeclaredMethods() :可以獲得class的成員方法
getDeclaredConstructors():可以獲得class的構(gòu)造函數(shù)

2.注解

Java代碼從編寫到運行會經(jīng)過三個大的時期:代碼編寫,編譯澡腾,讀取到JVM運行沸伏,針對三個時期分別有三類注解:

public enum RetentionPolicy {
    /**
     * Annotations are to be discarded by the compiler.
     */
    SOURCE,

    /**
     * Annotations are to be recorded in the class file by the compiler
     * but need not be retained by the VM at run time.  This is the default
     * behavior.
     */
    CLASS,

    /**
     * Annotations are to be recorded in the class file by the compiler and
     * retained by the VM at run time, so they may be read reflectively.
     *
     * @see java.lang.reflect.AnnotatedElement
     */
    RUNTIME
}

SOURCE:就是針對代碼編寫階段,比如@Override注解
CLASS:就是針對編譯階段动分,這個階段可以讓編譯器幫助我們?nèi)討B(tài)生成代碼
RUNTIME:就是針對讀取到JVM運行階段毅糟,這個可以結(jié)合反射使用,我們今天使用的注解也都是在這個階段澜公。

使用注解還需要指出注解使用的對象姆另,我們?nèi)タ丛创a知道有這么幾類:

public enum ElementType {
    /** Class, interface (including annotation type), or enum declaration */
    TYPE,

    /** Field declaration (includes enum constants) */
    FIELD,

    /** Method declaration */
    METHOD,

    /** Formal parameter declaration */
    PARAMETER,

    /** Constructor declaration */
    CONSTRUCTOR,

    /** Local variable declaration */
    LOCAL_VARIABLE,

    /** Annotation type declaration */
    ANNOTATION_TYPE,

    /** Package declaration */
    PACKAGE,

    /**
     * Type parameter declaration
     *
     * @since 1.8
     * @hide 1.8
     */
    TYPE_PARAMETER,

    /**
     * Use of a type
     *
     * @since 1.8
     * @hide 1.8
     */
    TYPE_USE
}

暈倒,會不會有點太多坟乾?不懼迹辐,其實我們經(jīng)常用到的也就這么幾個

TYPE 作用對象類/接口/枚舉
FIELD 成員變量
METHOD 成員方法
PARAMETER 方法參數(shù)
ANNOTATION_TYPE 注解的注解

那么怎么去定義一個注解呢?其實和定義接口非常類似甚侣,我們直接看我們栗子中用到的注解明吩。在栗子中會定義三類注解:

InjectView用于注入view,其實就是用來代替findViewById方法
Target指定了InjectView注解作用對象是成員變量
Retention指定了注解有效期直到運行時時期
value就是用來指定id殷费,也就是findViewById的參數(shù)

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface InjectView {
    int value();
}

onClick注解用于注入點擊事件印荔,其實用來代替setOnClickListener方法

Target指定了onClick注解作用對象是成員方法
Retention指定了onClick注解有效期直到運行時時期
value就是用來指定id低葫,也就是findViewById的參數(shù)

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@EventType(listenerType = View.OnClickListener.class, listenerSetter = "setOnClickListener", methodName = "onClick")
public @interface onClick {
    int[] value();
}

可以看到onClick注解上面還有一個自定義的注解EventType,它的定義如下:

Target指定了EventType注解作用對象是注解仍律,也就是注解的注解
Retention指定了EventType注解有效期直到運行時時期
listenerType用來指定點擊監(jiān)聽類型嘿悬,比如OnClickListener
listenerSetter用來指定設(shè)置點擊事件方法,比如setOnClickListener
methodName用來指定點擊事件發(fā)生后會回調(diào)的方法水泉,比如onClick

@Target(ElementType.ANNOTATION_TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface EventType {
    Class listenerType();
    String listenerSetter();
    String methodName();
}

3.動態(tài)代理

關(guān)于動態(tài)代理請參考上篇博客:http://www.reibang.com/p/b00ef12d53cc

4.綜合使用

光看理論是不是要睡著了善涨,我們先來個分割線休息下:

玄武門.jpg

ok,接下來我們來看個簡單的栗子草则,綜合使用上面說到的反射/注解/動態(tài)代理钢拧。先看下布局,很簡單就是兩個button,按鈕都是通過注解綁定炕横,點擊事件的監(jiān)聽也是通過注解+反射+動態(tài)代理的方式搞定娶靡。

<RelativeLayout
    android:id="@+id/activity_main"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.juexingzhe.proxytest.MainActivity">

    <Button
        android:id="@+id/bind_view_btn"
        android:layout_centerHorizontal="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/bind_view"/>

    <Button
        android:id="@+id/bind_click_btn"
        android:layout_centerInParent="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/bind_click"/>

</RelativeLayout>

-控件綁定實例化

我們先看下怎么綁定button這個成員變量,兩步搞定:

1.聲明成員變量看锉,在變量聲明上加上InjectView注解姿锭,value值就是button的id:R.id.bind_view_btn

    @InjectView(R.id.bind_view_btn)
    Button mBindView;

2.在onCreate中調(diào)用注入

Utils.injectView(this);

有的小伙伴就要笑了,這和findViewById一樣的也是兩步伯铣,吹牛吹到現(xiàn)在不是浪費時間嗎呻此?--->
重點來了,
如果有好多個控件腔寡,除了變量聲明外焚鲜,這個方法也只是一行代碼Utils.injectView(this);搞定*是不是厲害了?放前?忿磅?
我們?nèi)タ纯碪tils.injectView這個方法是怎么實現(xiàn)的,我在代碼中加了注釋凭语,應(yīng)該容易看懂葱她,前面為什么說不管多少控件這個方法都能搞定败明?

1.方法內(nèi)部首先拿到activity的所有成員變量掩蛤,
2.找到有InjectView注解的成員變量列荔,然后可以拿到button的id
3.通過反射activityClass.getMethod可以拿到findViewById方法
4.調(diào)用findViewById升略,參數(shù)就是id。
可以看出來最終都是通過findViewById進行控件的實例化

    public static void injectView(Activity activity) {
        if (null == activity) return;

        Class<? extends Activity> activityClass = activity.getClass();
        Field[] declaredFields = activityClass.getDeclaredFields();
        for (Field field : declaredFields) {
            if (field.isAnnotationPresent(InjectView.class)) {
                //找到InjectView注解的field
                InjectView annotation = field.getAnnotation(InjectView.class);
                //找到button的id
                int value = annotation.value();
                try {
                    //找到findViewById方法
                    Method findViewByIdMethod = activityClass.getMethod("findViewById", int.class);
                    findViewByIdMethod.setAccessible(true);
                    findViewByIdMethod.invoke(activity, value);
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }

    }

接下來看下點擊事件的綁定

-點擊事件的綁定

還是分成兩步

1.定義點擊事件發(fā)生時的回調(diào)方法, 需要綁定點擊事件的控件只需要將id賦值給onClick注解旋圆。

    @onClick({R.id.bind_click_btn, R.id.bind_view_btn})
    public void InvokeBtnClick(View view) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        switch (view.getId()) {
            case R.id.bind_click_btn:
                Log.i(Utils.TAG, "bind_click_btn Click");
                builder.setTitle(this.getClass().getSimpleName())
                        .setMessage("button onClick")
                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        }).create().show();
                break;
            case R.id.bind_view_btn:
                Log.i(Utils.TAG, "bind_view_btn Click");
                builder.setTitle(this.getClass().getSimpleName())
                        .setMessage("button binded")
                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        }).create().show();
                break;
        }
    }

2.在onCreate中調(diào)用注入

Utils.injectEvent(this);

反射+注解+動態(tài)代理就在injectEvent方法中纤泵,我們?nèi)タ纯此鼮槭裁催@么牛X,方法比較長铣口,我們一步步看:

1.首先就是獲取activity的所有成員方法getDeclaredMethods
2.找到有onClick注解的方法黔寇,拿到value就是注解點擊事件button的id
3.獲取onClick注解的注解EventType的參數(shù)偶器,從中可以拿到設(shè)定點擊事件方法setOnClickListener + 點擊事件的監(jiān)聽接口OnClickListener+點擊事件的回調(diào)方法onClick
4.在點擊事件發(fā)生的時候Android系統(tǒng)會觸發(fā)onClick事件,我們需要將事件的處理回調(diào)到注解的方法InvokeBtnClick,也就是代理的思想
5.通過動態(tài)代理Proxy.newProxyInstance實例化一個實現(xiàn)OnClickListener接口的代理屏轰,代理會在onClick事件發(fā)生的時候回調(diào)InvocationHandler進行處理
6.RealSubject就是activity术裸,因此我們傳入ProxyHandler實例化一個InvocationHandler,用來將onClick事件映射到activity中我們注解的方法InvokeBtnClick
7.通過反射實例化Button亭枷,findViewByIdMethod.invoke
8.通過Button.setOnClickListener(OnClickListener)進行設(shè)定點擊事件監(jiān)聽。

    public static void injectEvent(Activity activity) {
        if (null == activity) {
            return;
        }

        Class<? extends Activity> activityClass = activity.getClass();
        Method[] declaredMethods = activityClass.getDeclaredMethods();

        for (Method method : declaredMethods) {
            if (method.isAnnotationPresent(onClick.class)) {
                Log.i(Utils.TAG, method.getName());
                onClick annotation = method.getAnnotation(onClick.class);
                //獲取button id
                int[] value = annotation.value();
                //獲取EventType
                EventType eventType = annotation.annotationType().getAnnotation(EventType.class);
                Class listenerType = eventType.listenerType();
                String listenerSetter = eventType.listenerSetter();
                String methodName = eventType.methodName();

                //創(chuàng)建InvocationHandler和動態(tài)代理(代理要實現(xiàn)listenerType搀崭,這個例子就是處理onClick點擊事件)
                ProxyHandler proxyHandler = new ProxyHandler(activity);
                Object listener = Proxy.newProxyInstance(listenerType.getClassLoader(), new Class[]{listenerType}, proxyHandler);
                
                proxyHandler.mapMethod(methodName, method);
                try {
                    for (int id : value) {
                        //找到Button
                        Method findViewByIdMethod = activityClass.getMethod("findViewById", int.class);
                        findViewByIdMethod.setAccessible(true);
                        View btn = (View) findViewByIdMethod.invoke(activity, id);
                        //根據(jù)listenerSetter方法名和listenerType方法參數(shù)找到method
                        Method listenerSetMethod = btn.getClass().getMethod(listenerSetter, listenerType);
                        listenerSetMethod.setAccessible(true);
                        listenerSetMethod.invoke(btn, listener);
                    }
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }

看到上面這些步驟要留意:

為什么Proxy.newProxyInstance動態(tài)生成的代理能傳遞給Button.setOnClickListener叨粘?
因為Proxy傳入的參數(shù)中l(wèi)istenerType就是OnClickListener,所以Java為我們生成的代理會實現(xiàn)這個接口瘤睹,在onClick方法調(diào)用的時候會回調(diào)ProxyHandler中的invoke方法升敲,從而回調(diào)到activity中注解的方法。

ProxyHandler中主要是Invoke方法,在方法調(diào)用的時候?qū)ethod方法名和參數(shù)都打印出來轰传。

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        Log.i(Utils.TAG, "method name = " + method.getName() + " and args = " + Arrays.toString(args));

        Object handler = mHandlerRef.get();

        if (null == handler) return null;

        String name = method.getName();

        //將onClick方法的調(diào)用映射到activity 中的InvokeBtnClick()方法
        Method realMethod = mMethodHashMap.get(name);
        if (null != realMethod){
            return realMethod.invoke(handler, args);
        }

        return null;
    }

點擊運行結(jié)果:

運行結(jié)果.png

5.總結(jié)

文中用到的栗子比較簡單驴党,但是也闡明了反射+注解+動態(tài)代理的使用方法,可以發(fā)現(xiàn)通過這種方式會有比較好的擴展性获茬,后面即使增加控件也只是添加成員變量的聲明即可港庄。動態(tài)代理這篇文章中講到的比較少,還是建議先看下http://www.reibang.com/p/b00ef12d53cc

關(guān)于文中的栗子恕曲,有需要的我也已經(jīng)放到Github上了:https://github.com/juexingzhe/ProxyTest

謝謝鹏氧!

歡迎關(guān)注公眾號:JueCode

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市佩谣,隨后出現(xiàn)的幾起案子把还,更是在濱河造成了極大的恐慌,老刑警劉巖茸俭,帶你破解...
    沈念sama閱讀 222,627評論 6 517
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件吊履,死亡現(xiàn)場離奇詭異,居然都是意外死亡调鬓,警方通過查閱死者的電腦和手機艇炎,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,180評論 3 399
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來腾窝,“玉大人冕臭,你說我怎么就攤上這事⊙嘧叮” “怎么了辜贵?”我有些...
    開封第一講書人閱讀 169,346評論 0 362
  • 文/不壞的土叔 我叫張陵,是天一觀的道長归形。 經(jīng)常有香客問我托慨,道長,這世上最難降的妖魔是什么暇榴? 我笑而不...
    開封第一講書人閱讀 60,097評論 1 300
  • 正文 為了忘掉前任厚棵,我火速辦了婚禮蕉世,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘婆硬。我一直安慰自己狠轻,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 69,100評論 6 398
  • 文/花漫 我一把揭開白布彬犯。 她就那樣靜靜地躺著向楼,像睡著了一般。 火紅的嫁衣襯著肌膚如雪谐区。 梳的紋絲不亂的頭發(fā)上湖蜕,一...
    開封第一講書人閱讀 52,696評論 1 312
  • 那天,我揣著相機與錄音宋列,去河邊找鬼昭抒。 笑死,一個胖子當(dāng)著我的面吹牛炼杖,可吹牛的內(nèi)容都是我干的灭返。 我是一名探鬼主播,決...
    沈念sama閱讀 41,165評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼坤邪,長吁一口氣:“原來是場噩夢啊……” “哼婆殿!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起罩扇,我...
    開封第一講書人閱讀 40,108評論 0 277
  • 序言:老撾萬榮一對情侶失蹤婆芦,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后喂饥,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體消约,經(jīng)...
    沈念sama閱讀 46,646評論 1 319
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,709評論 3 342
  • 正文 我和宋清朗相戀三年员帮,在試婚紗的時候發(fā)現(xiàn)自己被綠了或粮。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,861評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡捞高,死狀恐怖氯材,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情硝岗,我是刑警寧澤氢哮,帶...
    沈念sama閱讀 36,527評論 5 351
  • 正文 年R本政府宣布,位于F島的核電站型檀,受9級特大地震影響冗尤,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 42,196評論 3 336
  • 文/蒙蒙 一裂七、第九天 我趴在偏房一處隱蔽的房頂上張望皆看。 院中可真熱鬧,春花似錦背零、人聲如沸腰吟。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,698評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽毛雇。三九已至,卻和暖如春倍啥,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背澎埠。 一陣腳步聲響...
    開封第一講書人閱讀 33,804評論 1 274
  • 我被黑心中介騙來泰國打工虽缕, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人蒲稳。 一個月前我還...
    沈念sama閱讀 49,287評論 3 379
  • 正文 我出身青樓氮趋,卻偏偏與公主長得像,于是被迫代替她去往敵國和親江耀。 傳聞我的和親對象是個殘疾皇子剩胁,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,860評論 2 361

推薦閱讀更多精彩內(nèi)容