前言
本章內(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)建靈活的代碼,這些代碼可以再運行時裝配塔橡,無需在組件之間進行源代碼鏈接梅割。但是反射使用不當(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進行控件的實例化
接下來看一下如何將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)代理的簡單使用惋砂,很多框架都會使用到這些高級屬性妒挎,這也是進階之路必修之課。