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

睡觉之前,为了更好地入眠,让我们来学习下反射+注解+动态代理的综合使用姿势。在上篇文章中我们简单的聊了下动态代理,今天我们结合反射和注解来一起看下。首先会先简单看下反射和注解,动态代理请参考上篇博客:www.jianshu.com/p/b00ef12d5…
然后会综合通过一个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.动态代理

关于动态代理请参考上篇博客:www.jianshu.com/p/b00ef12d5…

###4.综合使用
光看理论是不是要睡着了,我们先来个分割线休息下:

玄武门.jpg


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;
    }复制代码

点击运行结果:

运行结果.png

###5.总结
文中用到的栗子比较简单,但是也阐明了反射+注解+动态代理的使用方法,可以发现通过这种方式会有比较好的扩展性,后面即使增加控件也只是添加成员变量的声明即可。动态代理这篇文章中讲到的比较少,还是建议先看下www.jianshu.com/p/b00ef12d5…

关于文中的栗子,有需要的我也已经放到Github上了:github.com/juexingzhe/…

谢谢!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值