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

前言

本章內(nèi)容主要研究一下java高級特性-反射、android注解、和動態(tài)代理的使用,通過了解這些技術(shù),可以為了以后實(shí)現(xiàn)組件化或者Api hook相關(guān)的做一些技術(shù)儲備。

反射

  • 主要是指程序可以訪問,檢測和修改它本身狀態(tài)或行為的一種能力,并能根據(jù)自身行為的狀態(tài)和結(jié)果,調(diào)整或修改應(yīng)用所描述行為的狀態(tài)和相關(guān)的語義。

  • 反射是java中一種強(qiáng)大的工具,能夠使我們很方便的創(chuàng)建靈活的代碼,這些代碼可以再運(yùn)行時(shí)裝配,無需在組件之間進(jìn)行源代碼鏈接。但是反射使用不當(dāng)會成本很高

比較常用的方法

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

注解

Java代碼從編寫到運(yùn)行會經(jīng)過三個(gè)大的時(shí)期:代碼編寫,編譯,讀取到JVM運(yùn)行,針對三個(gè)時(shí)期分別有三類注解:

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:就是針對編譯階段,這個(gè)階段可以讓編譯器幫助我們?nèi)討B(tài)生成代碼
RUNTIME:就是針對讀取到JVM運(yùn)行階段,這個(gè)可以結(jié)合反射使用,我們今天使用的注解也都是在這個(gè)階段

使用注解還需要指出注解使用的對象

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
}

比較常用的方法

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

下面看下自己定義的三個(gè)注解

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

InjectView用于注入view,其實(shí)就是用來代替findViewById方法
Target指定了InjectView注解作用對象是成員變量
Retention指定了注解有效期直到運(yùn)行時(shí)時(shí)期
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注解用于注入點(diǎn)擊事件,其實(shí)用來代替setOnClickListener方法
Target指定了onClick注解作用對象是成員方法
Retention指定了onClick注解有效期直到運(yùn)行時(shí)時(shí)期
value就是用來指定id,也就是findViewById的參數(shù)

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

在onClikc里面有一個(gè)EventType定義
Target指定了EventType注解作用對象是注解,也就是注解的注解
Retention指定了EventType注解有效期直到運(yùn)行時(shí)時(shí)期
listenerType用來指定點(diǎn)擊監(jiān)聽類型,比如OnClickListener
listenerSetter用來指定設(shè)置點(diǎn)擊事件方法,比如setOnClickListener
methodName用來指定點(diǎn)擊事件發(fā)生后會回調(diào)的方法,比如onClick

綜合使用

接下來我用一個(gè)例子來演示如何使用反射、注解、和代理的綜合使用

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

在onCreate中調(diào)用注入U(xiǎn)tils.injectView(this);

我們看下Utils.injectView這個(gè)方法的內(nèi)部實(shí)現(xiàn)

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 獲取button id
            InjectView annotation = field.getAnnotation(InjectView.class);
            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.方法內(nèi)部首先拿到activity的所有成員變量,
2.找到有InjectView注解的成員變量,然后可以拿到button的id
3.通過反射activityClass.getMethod可以拿到findViewById方法
4.調(diào)用findViewById,參數(shù)就是id。
可以看出來最終都是通過findViewById進(jìn)行控件的實(shí)例化

接下來看一下如何將onClick方法的調(diào)用映射到activity 中的invokeClick()方法

首先在onCreate中調(diào)用注入 Utils.injectEvent(this);

@onClick({R.id.btn_bind_click, R.id.btn_bind_view})
public void invokeClick(View view) {
    switch (view.getId()) {
        case R.id.btn_bind_click:
            Log.i(Utils.TAG, "bind_click_btn Click");

            Toast.makeText(MainActivity.this,"button onClick",Toast.LENGTH_SHORT).show();

            break;
        case R.id.btn_bind_view:
            Log.i(Utils.TAG, "bind_view_btn Click");
            Toast.makeText(MainActivity.this,"button binded",Toast.LENGTH_SHORT).show();

            break;

    }
}

反射+注解+動態(tài)代理就在injectEvent方法中,我們現(xià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);
            //get button id
            int[] value = annotation.value();
            //get 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)代理(代理要實(shí)現(xiàn)listenerType,這個(gè)例子就是處理onClick點(diǎn)擊事件)
            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();
            }
        }

    }
}

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

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

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

@Override
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 中的invokeClick()方法
    Method realMethod = mMethodHashMap.get(name);
    if (null != realMethod){
        return realMethod.invoke(handler, args);
    }

    return null;
}

點(diǎn)擊運(yùn)行結(jié)果

總結(jié)

通過上面的例子可以看到反射+注解+動態(tài)代理的簡單使用,很多框架都會使用到這些高級屬性,這也是進(jìn)階之路必修之課。


點(diǎn)贊加關(guān)注是給我最大的鼓勵(lì)!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容