当前位置 : 主页 > 手机开发 > android >

Android 反射注解与动态代理综合使用详解

来源:互联网 收集:自由互联 发布时间:2021-08-03
前言 本章内容主要研究一下java高级特性-反射、android注解、和动态代理的使用,通过了解这些技术,可以为了以后实现组件化或者Api hook相关的做一些技术储备。 反射 主要是指程序可

前言

本章内容主要研究一下java高级特性-反射、android注解、和动态代理的使用,通过了解这些技术,可以为了以后实现组件化或者Api hook相关的做一些技术储备。

反射

主要是指程序可以访问,检测和修改它本身状态或行为的一种能力,并能根据自身行为的状态和结果,调整或修改应用所描述行为的状态和相关的语义。

反射是java中一种强大的工具,能够使我们很方便的创建灵活的代码,这些代码可以再运行时装配,无需在组件之间进行源代码链接。但是反射使用不当会成本很高

比较常用的方法

  1. getDeclaredFields(): 可以获得class的成员变量
  2. getDeclaredMethods() :可以获得class的成员方法
  3. getDeclaredConstructors():可以获得class的构造函数

注解

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
 }

  1. SOURCE:就是针对代码编写阶段,比如@Override注解
  2. CLASS:就是针对编译阶段,这个阶段可以让编译器帮助我们去动态生成代码
  3. 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
}

比较常用的方法

  1. TYPE 作用对象类/接口/枚举
  2. FIELD 成员变量
  3. METHOD 成员方法
  4. PARAMETER 方法参数
  5. ANNOTATION_TYPE 注解的注解

下面看下自己定义的三个注解

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
 public @interface InjectView {
 int value();
}

InjectView用于注入view,其实就是用来代替findViewById方法

Target指定了InjectView注解作用对象是成员变量

Retention指定了注解有效期直到运行时时期

value就是用来指定id,也就是findViewById的参数

@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的参数

@Target(ElementType.ANNOTATION_TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface EventType {
Class listenerType();
String listenerSetter();
String methodName();
}

在onClikc里面有一个EventType定义

Target指定了EventType注解作用对象是注解,也就是注解的注解

Retention指定了EventType注解有效期直到运行时时期

listenerType用来指定点击监听类型,比如OnClickListener

listenerSetter用来指定设置点击事件方法,比如setOnClickListener

methodName用来指定点击事件发生后会回调的方法,比如onClick

综合使用

接下来我用一个例子来演示如何使用反射、注解、和代理的综合使用

@InjectView(R.id.bind_view_btn)
 Button mBindView;

在onCreate中调用注入Utils.injectView(this);

我们看下Utils.injectView这个方法的内部实现

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.方法内部首先拿到activity的所有成员变量,
2.找到有InjectView注解的成员变量,然后可以拿到button的id
3.通过反射activityClass.getMethod可以拿到findViewById方法
4.调用findViewById,参数就是id。

可以看出来最终都是通过findViewById进行控件的实例化

接下来看一下如何将onClick方法的调用映射到activity 中的invokeClick()方法

首先在onCreate中调用注入 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;
 }
}

反射+注解+动态代理就在injectEvent方法中,我们现在去揭开女王的神秘面纱

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();

   //创建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();
   }
  }
 }
}

1.首先就是获取activity的所有成员方法getDeclaredMethods
2.找到有onClick注解的方法,拿到value就是注解点击事件button的id
3.获取onClick注解的注解EventType的参数,从中可以拿到设定点击事件方法setOnClickListener + 点击事件的监听接口OnClickListener+点击事件的回调方法onClick
4.在点击事件发生的时候Android系统会触发onClick事件,我们需要将事件的处理回调到注解的方法invokeClick,也就是代理的思想
5.通过动态代理Proxy.newProxyInstance实例化一个实现OnClickListener接口的代理,代理会在onClick事件发生的时候回调InvocationHandler进行处理
6.RealSubject就是activity,因此我们传入ProxyHandler实例化一个InvocationHandler,用来将onClick事件映射到activity中我们注解的方法InvokeBtnClick
7.通过反射实例化Button,findViewByIdMethod.invoke
8.通过Button.setOnClickListener(OnClickListener)进行设定点击事件监听。

接着可能会思考为什么Proxy.newProxyInstance动态生成的代理能传递给Button.setOnClickListener?

因为Proxy传入的参数中listenerType就是OnClickListener,所以Java为我们生成的代理会实现这个接口,在onClick方法调用的时候会回调ProxyHandler中的invoke方法,从而回调到activity中注解的方法。

ProxyHandler中主要是Invoke方法,在方法调用的时候将method方法名和参数都打印出来。

@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方法的调用映射到activity 中的invokeClick()方法
 Method realMethod = mMethodHashMap.get(name);
 if (null != realMethod){
  return realMethod.invoke(handler, args);
 }
 return null;
}

点击运行结果

总结

通过上面的例子可以看到反射+注解+动态代理的简单使用,很多框架都会使用到这些高级属性,这也是进阶之路必修之课。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持自由互联。

网友评论