ButterKnife源码分析

ButterKnife 主要解决 findviewById ,set...Click, 以及资源注入ioc,编译时注解 .
ButterKnife的注解在 butterknife-annotations下,

@Retention(CLASS) @Target(FIELD)
public @interface Bind {
  /** View ID to which the field will be bound. */
  int[] value();
}

编译时注解 直接生成辅助类,不需要反射,不影响性能,通过 AbstractProcessor 类
运行时注解 通过反射调用 ,会影响性能(很少)

解析注释:

public final class ButterKnifeProcessor extends AbstractProcessor {
...
}//注解处理器
  @Override public synchronized void init(ProcessingEnvironment env) {
    super.init(env);
//  init方法,获得一些工具类
  }
  @Override public Set<String> getSupportedAnnotationTypes() {
    Set<String> types = new LinkedHashSet<String>();
       ...
    return types;
  }//返回该注解处理器所支持的注解集合

关键代码:

  @Override public boolean process(Set<? extends TypeElement> elements, RoundEnvironment env) {
    Map<TypeElement, BindingClass> targetClassMap = findAndParseTargets(env);
    for (Map.Entry<TypeElement, BindingClass> entry : targetClassMap.entrySet()) {
      TypeElement typeElement = entry.getKey();
      BindingClass bindingClass = entry.getValue();
      try {
        JavaFileObject jfo = filer.createSourceFile(bindingClass.getFqcn(), typeElement);
        Writer writer = jfo.openWriter();
        writer.write(bindingClass.brewJava());
        writer.flush();
        writer.close();
      } catch (IOException e) {
        error(typeElement, "Unable to write view binder for type %s: %s", typeElement,
            e.getMessage());
      }
    }
    return true;
  }

实现都在其他私有方法中,本方法主要两个作用:
1.扫描所有注解,生成 typeElement为key bi,ndingClass为value的Map;
2.根据生成的map,遍历后通过filter 生成对应的辅助类源码。

findAndParseTargets:
扫描所有的ButterKnife注解,并且生成以TypeElement为键,BindingSet为值的HashMap

动态生成class 的方法:(opt)

ClassName classname=ClassName.get("包名","类名");
TypeSpec.Builder classBuilder=TypeSpec.classBuilder(“类名”)
.addModifiers(modifier.PUBLIC ,modifier,FINAL)
.addFileComment("text----text");
.addSuperinterface(ClassName);
MethodSpec.Builder  method=MethodSpec.methodBuilder("方法名").addAnnotation(Override.class).add...
classBuilder.addMethod(method);
javaFile.builder(包名,classBuilder.build()).build().writeto(mFiler);

实现必要的方法(如 实现方法)
构造函数
生成类
写入


ButterKnife.bind(this);

依次调用
static void bind(Object target, Object source, Finder finder)---》
findViewBinderForClass(Class<?> cls) 「先去binders中去找,如果找到则返回,否则 动态生成对应的 className+$$ViewBinder」 ---》
返回一个ViewBinder<Object> 对象

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 博文出处:ButterKnife源码分析,欢迎大家关注我的博客,谢谢! 0x01 前言 在程序开发的过程中,总会有...
    俞其荣阅读 2,074评论 1 18
  • butterknife注解框架相信很多同学都在用,但是你真的了解它的实现原理吗?那么今天让我们来看看它到底是怎么实...
    打不死的小强qz阅读 670评论 0 4
  • 主目录见:Android高级进阶知识(这是总目录索引) 前面我们已经讲完[编译期注解的使用例子]大家应该对这个流程...
    ZJ_Rocky阅读 1,500评论 0 8
  • 喜欢国画中大片的留白,虽然只有寥寥几笔却有无限的想象空间。以无胜有的留白艺术,具有很高的审美价值,正所谓“此处无物...
    陈磊愫言阅读 1,549评论 15 42
  • 关于青春,没能留下太多回忆。关于你,也没能有太多的故事。时光总是静静流淌,记忆也会慢慢消散。渐渐,忘掉了那份憧憬...
    随风而铃阅读 307评论 0 0