依赖注入——Annotation

在Android开发中,为了避免重复的代码,如:

   Button btn;
   btn = (Button)findViewById(R.id.btn);

在代码中可以使用如下的方式:

@InjectView(R.id.user) 
EditText username;

这里使用的是Butter Knife库

但是在使用上面类似的库时,可能会感到不放心,想了解它们大概的实现原理,这时就需要复习一下Java的Annotation的相关知识。
这里是一篇讲解的文章,但是看起来的先过不如看书来的清晰,还好别人有一本《疯狂java讲义》,可以拿来看看。。。

之后模拟了依赖注入的过程,其中涉及到Annotation的定义和反射机制。

总之,使用定义的Annotion进行注解,然后通过反射对注解进行处理。

注解示例:

    @CustomInject(id = R.id.btn)
    private Button btn;

    @CustomInject(id = R.id.text)
    private TextView text;

处理示例:

public class InjectTool {
    public static void process(Activity activity){
        try{
            Class clazz = activity.getClass();
            for(Field field : clazz.getDeclaredFields()){
                // Setting this to true prevents IllegalAccessExceptions.
                field.setAccessible(true);

                // Returns, for this element, the annotation with the specified type, or null if no annotation with the specified type is present
                CustomInject customInject = field.getAnnotation(CustomInject.class);

                if(customInject!=null){
                    // 获取@CustomInject(id = R.id.btn)中id的值
                    int id = customInject.id();

                    if (id>0){
                        // 赋值
                        field.set(activity,activity.findViewById(id));
                    }
                }
            }
        }catch (Exception exception){
            exception.printStackTrace();
        }
    }
}

下面是完整的代码地址
https://github.com/orgcheng/CustomAnnotationInject

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值