睡覺之前,為了更好地入眠,讓我們來學習下反射+注解+動態代理的綜合使用姿勢。在上篇文章中我們簡單的聊了下動態代理,今天我們結合反射和注解來一起看下。首先會先簡單看下反射和注解,動態代理請參考上篇博客:http://www.lxweimin.com/p/b00ef12d53cc
然后會綜合通過一個Android的小栗子進行實戰。
1.反射
先儲備下理論知識,具體的應用可以看后面的栗子。
利用Java的反射可以在運行狀態下把一個class內部的成員方法/字段和構造函數全部獲得,甚至可以進行實例化,調用內部方法。是不是很厲害的樣子?
比較常用的方法:
getDeclaredFields(): 可以獲得class的成員變量
getDeclaredMethods() :可以獲得class的成員方法
getDeclaredConstructors():可以獲得class的構造函數
2.注解
Java代碼從編寫到運行會經過三個大的時期:代碼編寫,編譯,讀取到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:就是針對編譯階段,這個階段可以讓編譯器幫助我們去動態生成代碼
RUNTIME:就是針對讀取到JVM運行階段,這個可以結合反射使用,我們今天使用的注解也都是在這個階段。
使用注解還需要指出注解使用的對象,我們去看源碼知道有這么幾類:
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 方法參數
ANNOTATION_TYPE 注解的注解
那么怎么去定義一個注解呢?其實和定義接口非常類似,我們直接看我們栗子中用到的注解。在栗子中會定義三類注解:
InjectView用于注入view,其實就是用來代替findViewById方法
Target指定了InjectView注解作用對象是成員變量
Retention指定了注解有效期直到運行時時期
value就是用來指定id,也就是findViewById的參數
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface InjectView {
int value();
}
onClick注解用于注入點擊事件,其實用來代替setOnClickListener方法
Target指定了onClick注解作用對象是成員方法
Retention指定了onClick注解有效期直到運行時時期
value就是用來指定id,也就是findViewById的參數
@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用來指定點擊監聽類型,比如OnClickListener
listenerSetter用來指定設置點擊事件方法,比如setOnClickListener
methodName用來指定點擊事件發生后會回調的方法,比如onClick
@Target(ElementType.ANNOTATION_TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface EventType {
Class listenerType();
String listenerSetter();
String methodName();
}
3.動態代理
關于動態代理請參考上篇博客:http://www.lxweimin.com/p/b00ef12d53cc
4.綜合使用
光看理論是不是要睡著了,我們先來個分割線休息下:
ok,接下來我們來看個簡單的栗子,綜合使用上面說到的反射/注解/動態代理。先看下布局,很簡單就是兩個button,按鈕都是通過注解綁定,點擊事件的監聽也是通過注解+反射+動態代理的方式搞定。
<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中調用注入
Utils.injectView(this);
有的小伙伴就要笑了,這和findViewById一樣的也是兩步,吹牛吹到現在不是浪費時間嗎?--->
重點來了,如果有好多個控件,除了變量聲明外,這個方法也只是一行代碼Utils.injectView(this);搞定*是不是厲害了???
我們去看看Utils.injectView這個方法是怎么實現的,我在代碼中加了注釋,應該容易看懂,前面為什么說不管多少控件這個方法都能搞定?
1.方法內部首先拿到activity的所有成員變量,
2.找到有InjectView注解的成員變量,然后可以拿到button的id
3.通過反射activityClass.getMethod可以拿到findViewById方法
4.調用findViewById,參數就是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.定義點擊事件發生時的回調方法, 需要綁定點擊事件的控件只需要將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中調用注入
Utils.injectEvent(this);
反射+注解+動態代理就在injectEvent方法中,我們去看看它為什么這么牛X,方法比較長,我們一步步看:
1.首先就是獲取activity的所有成員方法getDeclaredMethods
2.找到有onClick注解的方法,拿到value就是注解點擊事件button的id
3.獲取onClick注解的注解EventType的參數,從中可以拿到設定點擊事件方法setOnClickListener + 點擊事件的監聽接口OnClickListener+點擊事件的回調方法onClick
4.在點擊事件發生的時候Android系統會觸發onClick事件,我們需要將事件的處理回調到注解的方法InvokeBtnClick,也就是代理的思想
5.通過動態代理Proxy.newProxyInstance實例化一個實現OnClickListener接口的代理,代理會在onClick事件發生的時候回調InvocationHandler進行處理
6.RealSubject就是activity,因此我們傳入ProxyHandler實例化一個InvocationHandler,用來將onClick事件映射到activity中我們注解的方法InvokeBtnClick
7.通過反射實例化Button,findViewByIdMethod.invoke
8.通過Button.setOnClickListener(OnClickListener)進行設定點擊事件監聽。
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();
//創建InvocationHandler和動態代理(代理要實現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);
//根據listenerSetter方法名和listenerType方法參數找到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動態生成的代理能傳遞給Button.setOnClickListener?
因為Proxy傳入的參數中listenerType就是OnClickListener,所以Java為我們生成的代理會實現這個接口,在onClick方法調用的時候會回調ProxyHandler中的invoke方法,從而回調到activity中注解的方法。
ProxyHandler中主要是Invoke方法,在方法調用的時候將method方法名和參數都打印出來。
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方法的調用映射到activity 中的InvokeBtnClick()方法
Method realMethod = mMethodHashMap.get(name);
if (null != realMethod){
return realMethod.invoke(handler, args);
}
return null;
}
點擊運行結果:
5.總結
文中用到的栗子比較簡單,但是也闡明了反射+注解+動態代理的使用方法,可以發現通過這種方式會有比較好的擴展性,后面即使增加控件也只是添加成員變量的聲明即可。動態代理這篇文章中講到的比較少,還是建議先看下http://www.lxweimin.com/p/b00ef12d53cc
關于文中的栗子,有需要的我也已經放到Github上了:https://github.com/juexingzhe/ProxyTest
謝謝!
歡迎關注公眾號:JueCode