国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 系統(tǒng) > Android > 正文

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

2019-10-22 18:12:57
字體:
供稿:網(wǎng)友

前言

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

反射

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

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

比較常用的方法

  1. getDeclaredFields(): 可以獲得class的成員變量
  2. getDeclaredMethods() :可以獲得class的成員方法
  3. getDeclaredConstructors():可以獲得class的構造函數(shù)

注解

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

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

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}

比較常用的方法

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

下面看下自己定義的三個注解

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

InjectView用于注入view,其實就是用來代替findViewById方法

Target指定了InjectView注解作用對象是成員變量

Retention指定了注解有效期直到運行時時期

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注解用于注入點擊事件,其實用來代替setOnClickListener方法

Target指定了onClick注解作用對象是成員方法

Retention指定了onClick注解有效期直到運行時時期

value就是用來指定id,也就是findViewById的參數(shù)

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

在onClikc里面有一個EventType定義

Target指定了EventType注解作用對象是注解,也就是注解的注解

Retention指定了EventType注解有效期直到運行時時期

listenerType用來指定點擊監(jiān)聽類型,比如OnClickListener

listenerSetter用來指定設置點擊事件方法,比如setOnClickListener

methodName用來指定點擊事件發(fā)生后會回調(diào)的方法,比如onClick

綜合使用

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

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

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

我們看下Utils.injectView這個方法的內(nèi)部實現(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進行控件的實例化

接下來看一下如何將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)代理(代理要實現(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();   }  } }}

1.首先就是獲取activity的所有成員方法getDeclaredMethods
2.找到有onClick注解的方法,拿到value就是注解點擊事件button的id
3.獲取onClick注解的注解EventType的參數(shù),從中可以拿到設定點擊事件方法setOnClickListener + 點擊事件的監(jiān)聽接口OnClickListener+點擊事件的回調(diào)方法onClick
4.在點擊事件發(fā)生的時候Android系統(tǒng)會觸發(fā)onClick事件,我們需要將事件的處理回調(diào)到注解的方法invokeClick,也就是代理的思想
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)進行設定點擊事件監(jiān)聽。

接著可能會思考為什么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ù)都打印出來。

@Overridepublic 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;}

點擊運行結(jié)果

Android,反射注解,動態(tài)代理

總結(jié)

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

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持VEVB武林網(wǎng)。


注:相關教程知識閱讀請移步到Android開發(fā)頻道。
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 丹凤县| 松原市| 宝丰县| 洪洞县| 长岛县| 阜新市| 益阳市| 承德市| 乳山市| 邳州市| 镇康县| 博野县| 内丘县| 阿拉尔市| 泗阳县| 宝坻区| 嵩明县| 巴林右旗| 锦州市| 南华县| 敖汉旗| 白河县| 盐池县| 宜都市| 尼木县| 广河县| 当阳市| 孝感市| 荆州市| 鹤山市| 邓州市| 牙克石市| 鲁甸县| 鄂尔多斯市| 寿宁县| 安平县| 邮箱| 开鲁县| 勃利县| 玉山县| 新建县|