睡覺之前悦昵,為了更好地入眠,讓我們來學(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.綜合使用
光看理論是不是要睡著了善涨,我們先來個分割線休息下:
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é)果:
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