您好,登錄后才能下訂單哦!
今天就跟大家聊聊有關(guān)怎么在Android中使用反射注解與動態(tài)代理,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。
反射
主要是指程序可以訪問,檢測和修改它本身狀態(tài)或行為的一種能力,并能根據(jù)自身行為的狀態(tài)和結(jié)果,調(diào)整或修改應(yīng)用所描述行為的狀態(tài)和相關(guān)的語義。
反射是java中一種強(qiáng)大的工具,能夠使我們很方便的創(chuàng)建靈活的代碼,這些代碼可以再運行時裝配,無需在組件之間進(jìn)行源代碼鏈接。但是反射使用不當(dā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進(jìn)行控件的實例化
接下來看一下如何將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進(jìn)行處理
6.RealSubject就是activity,因此我們傳入ProxyHandler實例化一個InvocationHandler,用來將onClick事件映射到activity中我們注解的方法InvokeBtnClick
7.通過反射實例化Button,findViewByIdMethod.invoke
8.通過Button.setOnClickListener(OnClickListener)進(jìn)行設(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é)果
看完上述內(nèi)容,你們對怎么在Android中使用反射注解與動態(tài)代理有進(jìn)一步的了解嗎?如果還想了解更多知識或者相關(guān)內(nèi)容,請關(guān)注億速云行業(yè)資訊頻道,感謝大家的支持。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。