Android 反射注解與動態(tài)代理綜合使用詳解
前言
本章內(nèi)容主要研究一下java高級特性-反射、android注解、和動態(tài)代理的使用,通過了解這些技術(shù),可以為了以后實現(xiàn)組件化或者Api hook相關(guān)的做一些技術(shù)儲備。
反射
主要是指程序可以訪問,檢測和修改它本身狀態(tài)或行為的一種能力,并能根據(jù)自身行為的狀態(tài)和結(jié)果,調(diào)整或修改應(yīng)用所描述行為的狀態(tài)和相關(guān)的語義。
反射是java中一種強大的工具,能夠使我們很方便的創(chuàng)建靈活的代碼,這些代碼可以再運行時裝配,無需在組件之間進行源代碼鏈接。但是反射使用不當會成本很高
比較常用的方法
- getDeclaredFields(): 可以獲得class的成員變量
- getDeclaredMethods() :可以獲得class的成員方法
- getDeclaredConstructors():可以獲得class的構(gòu)造函數(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 }
- SOURCE:就是針對代碼編寫階段,比如@Override注解
- CLASS:就是針對編譯階段,這個階段可以讓編譯器幫助我們?nèi)討B(tài)生成代碼
- 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 }
比較常用的方法
- TYPE 作用對象類/接口/枚舉
- FIELD 成員變量
- METHOD 成員方法
- PARAMETER 方法參數(shù)
- 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用來指定設(shè)置點擊事件方法,比如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ù),從中可以拿到設(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)進行設(shè)定點擊事件監(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ù)都打印出來。
@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; }
點擊運行結(jié)果
總結(jié)
通過上面的例子可以看到反射+注解+動態(tài)代理的簡單使用,很多框架都會使用到這些高級屬性,這也是進階之路必修之課。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Android 開發(fā)中fragment預(yù)加載問題
這篇文章主要介紹了Android 開發(fā)中fragment預(yù)加載問題的相關(guān)資料,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2017-01-01Android開發(fā)中計算器的sin、cos及tan值計算問題分析
這篇文章主要介紹了Android開發(fā)中計算器的sin、cos及tan值計算問題,結(jié)合實例形式分析了Android三角函數(shù)運算中的弧度與角度計算問題與相關(guān)解決方法,需要的朋友可以參考下2017-11-11Android Studio中導(dǎo)入module的方法(簡單版)
這篇文章主要介紹了AndroidStudio中導(dǎo)入module的方法,本文是一篇簡易版的教程,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2018-01-01Android中關(guān)于屏幕的三個小眾知識(寬屏適配、禁止截屏和保持屏幕常亮)
這篇文章主要給大家介紹了Android中關(guān)于屏幕的三個小眾知識,分別是寬屏適配、禁止截屏和保持屏幕常亮的相關(guān)資料,文中通過示例代碼介紹的非常詳細,需要的朋友們可以參考學(xué)習(xí),下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。2017-12-12Android實現(xiàn)使用微信登錄第三方APP的方法
這篇文章主要介紹了Android實現(xiàn)使用微信登錄第三方APP的方法,結(jié)合實例形式分析了Android微信登錄APP的操作步驟與具體功能實現(xiàn)技巧,需要的朋友可以參考下2016-11-11