IOC框架

作者: Poseidon_Wang | 来源:发表于2016-05-23 18:53 被阅读163次

    IOC(Inversion Of Control)框架,已经是比较成熟,比较老的技术了。市面上也有许多成熟的产品,比如butterKnife,ButterKnife,RoboGuice...如果我们的项目对这块依赖不是很大,我们可以尝试自己写一个IOC框架。当然其实说白了就是一个反射框架,所以我们首先来讲讲注解,然后通过注解反射。

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

    以上就是一个简单的注解例子,通常用@interface来标记注解标记

    public enum ElementType {  
        /** 
         * Class, interface or enum declaration. 
         */  
        TYPE,  
        /** 
         * Field declaration. 
         */  
        FIELD,  
        /** 
         * Method declaration. 
         */  
        METHOD,  
        /** 
         * Parameter declaration. 
         */  
        PARAMETER,  
        /** 
         * Constructor declaration. 
         */  
        CONSTRUCTOR,  
        /** 
         * Local variable declaration. 
         */  
        LOCAL_VARIABLE,  
        /** 
         * Annotation type declaration. 
         */  
        ANNOTATION_TYPE,  
        /** 
         * Package declaration. 
         */  
        PACKAGE  
    }  
    

    关于上述Target参数的解释

    public enum RetentionPolicy {  
        /** 
         * Annotation is only available in the source code. 
         */  
        SOURCE,  
        /** 
         * Annotation is available in the source code and in the class file, but not 
         * at runtime. This is the default policy. 
         */  
        CLASS,  
        /** 
         * Annotation is available in the source code, the class file and is 
         * available at runtime. 
         */  
        RUNTIME  
    }  
    

    Retention参数解释
    知道了这些我们已经可以编写一个简单的IOC框架了

    注解解析代码
    1. 首先我们需要在activity注入布局文件后进行解析,否则是找不到这些id的
    2. 然后我们根据反射方法获取该activity下所有字段
    Field[] fields = activity.getClass().getDeclaredFields();
    
    1. 然后遍历这些字段是否带了我们定义的注解
    2. 若带了该注解,则获取其值
    3. 根据该值我们调用activity的findViewById(id)方法绑定View
    4. 然后再查询有无click方法,若有继续调用Method.invoke方法
      附上代码github ioc框架

    下回我们不用反射,用预编译来生成IOC框架,速度上会有较大提升,目前比较流行的Dagger2就是用的预编译技术

    相关文章

      网友评论

          本文标题:IOC框架

          本文链接:https://www.haomeiwen.com/subject/lsgarttx.html