添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

我们已经把基本知识都搞定了,也能够实现简单的功能。作为这个系列的最后一篇,我们来看看Butterknife的实现原理。

运行Demo也在下载的包中,大家自己运行看下效果就可以了。首先我们来看看整个工程的结构:

下载的源码中的工程还是不少的,但是图中被选中的蓝色工程才是我们分析的重点,其他的三个光看名字可以推断出,是给gradle和lint工具使用的,这里就不做介绍了。

除了sample,其他的三个都是库,是不是觉得这个命名规则看上去十分熟悉,跟我们的demo很像,这样分析起来就容易多了,来看看Annotation中都有哪些注解:

卧槽槽,好多的注解,看名称我们就明白注解的作用,所以直接就找BindView,弄懂了一个,其他的也迎刃而解。

BindView源码:

* Bind a field to the view for the specified ID. The view will automatically be cast to the field * type. * <pre><code> * {@literal @}BindView(R.id.title) TextView title; * </code></pre> @Retention (CLASS) @Target (FIELD) public @interface BindView { /** View ID to which the field will be bound. */ @IdRes int value ();

一个资源id的value值,跟我们的没有什么区别,那就直接打开compiler,看看里面的Processor到底做了什么。

ButterKnife的代码还是不少,主要是看process方法:

@Override 
public boolean process(Set<? extends TypeElement> elements, RoundEnvironment env) {
    // 重点看这里
    Map<TypeElement, BindingSet> bindingMap = findAndParseTargets(env);
    // 循环输出生成的文件
    for (Map.Entry<TypeElement, BindingSet> entry : bindingMap.entrySet()) {
      TypeElement typeElement = entry.getKey();
      BindingSet binding = entry.getValue();
      JavaFile javaFile = binding.brewJava(sdk);
      try {
        javaFile.writeTo(filer);
      } catch (IOException e) {
        error(typeElement, "Unable to write binding for type %s: %s", typeElement, e.getMessage());
    return false;

ButterKnife 封装的还是很仔细的,上面的代码主要是for循环输出编译出来的文件,对注解的操作都在 findAndParseTargets(env)这个方法里,那就去看看这个方法:

private Map<TypeElement, BindingSet> findAndParseTargets(RoundEnvironment env) {
    Map<TypeElement, BindingSet.Builder> builderMap = new LinkedHashMap<>();
    Set<TypeElement> erasedTargetNames = new LinkedHashSet<>();
    scanForRClasses(env);
    // 重点看这里
    // Process each @BindView element.
    for (Element element : env.getElementsAnnotatedWith(BindView.class)) {
      // we don't SuperficialValidation.validateElement(element)
      // so that an unresolved View type can be generated by later processing rounds
      try {
      // 重点看这里
        parseBindView(element, builderMap, erasedTargetNames);
      } catch (Exception e) {
        logParsingError(element, BindView.class, e);
    return bindingMap;

这个方法里是处理各种注解的主方法,多余的我都删掉了,这个方法主要是获取所有的注解,然后解析注解,把注解的所有信息封装到BindingSet中,那么解析的具体操作应该就在parseBindView(element, builderMap, erasedTargetNames)中,接着往下看:

* 解析BindView注解的方法 private void parseBindView(Element element, Map<TypeElement, BindingSet.Builder> builderMap, Set<TypeElement> erasedTargetNames) { TypeElement enclosingElement = (TypeElement) element.getEnclosingElement(); // Start by verifying common generated code restrictions. // 验证注解使用的正确性 // 检查是否注解的是属性,包使用是否正确 boolean hasError = isInaccessibleViaGeneratedCode(BindView.class, "fields", element) || isBindingInWrongPackage(BindView.class, element); // Verify that the target type extends from View. // 检查注解元素的类型是否View或者是接口 TypeMirror elementType = element.asType(); if (elementType.getKind() == TypeKind.TYPEVAR) { TypeVariable typeVariable = (TypeVariable) elementType; elementType = typeVariable.getUpperBound(); Name qualifiedName = enclosingElement.getQualifiedName(); Name simpleName = element.getSimpleName(); if (!isSubtypeOfType(elementType, VIEW_TYPE) && !isInterface(elementType)) { if (elementType.getKind() == TypeKind.ERROR) { note(element, "@%s field with unresolved type (%s) " + "must elsewhere be generated as a View or interface. (%s.%s)", BindView.class.getSimpleName(), elementType, qualifiedName, simpleName); } else { error(element, "@%s fields must extend from View or be an interface. (%s.%s)", BindView.class.getSimpleName(), qualifiedName, simpleName); hasError = true; if (hasError) { return; // 终于得到注解的信息了 // Assemble information on the field. int id = element.getAnnotation(BindView.class).value(); BindingSet.Builder builder = builderMap.get(enclosingElement); QualifiedId qualifiedId = elementToQualifiedId(element, id); if (builder != null) { String existingBindingName = builder.findExistingBindingName(getId(qualifiedId)); // 从已经解析过的注解信息中查看是否已经使用了这个id if (existingBindingName != null) { error(element, "Attempt to use @%s for an already bound ID %d on '%s'. (%s.%s)", BindView.class.getSimpleName(), id, existingBindingName, enclosingElement.getQualifiedName(), element.getSimpleName()); return; // 没有就创建一个BindSet放入到集合中, //getOrCreateBindingBuilder方法已经复制到下面 else { builder = getOrCreateBindingBuilder(builderMap, enclosingElement); String name = simpleName.toString(); TypeName type = TypeName.get(elementType); boolean required = isFieldRequired(element); // id作为属性放入到BindSet中 builder.addField(getId(qualifiedId), new FieldViewBinding(name, type, required)); // Add the type-erased version to the valid binding targets set. erasedTargetNames.add(enclosingElement); * 创建BindSet.Buidler信息 private BindingSet.Builder getOrCreateBindingBuilder( Map<TypeElement, BindingSet.Builder> builderMap, TypeElement enclosingElement) { BindingSet.Builder builder = builderMap.get(enclosingElement); // 放到所有的注解的信息的集合中 if (builder == null) { builder = BindingSet.newBuilder(enclosingElement); builderMap.put(enclosingElement, builder); return builder;

到这里解析就算是结束了,然后我们去找找生成java文件的方法,也就是刚才的for循环,因为也会跳好几层,所以直接看最重要的部分:

* 生成类文件 private TypeSpec createType(int sdk) { // 类名 TypeSpec.Builder result = TypeSpec.classBuilder(bindingClassName.simpleName()) .addModifiers(PUBLIC); if (isFinal) { result.addModifiers(FINAL); // 继承关系和应用接口信息 if (parentBinding != null) { result.superclass(parentBinding.bindingClassName); } else { result.addSuperinterface(UNBINDER); // 属性信息 if (hasTargetField()) { result.addField(targetTypeName, "target", PRIVATE); // 根据类型,添加不一样的构造方法 if (isView) { result.addMethod(createBindingConstructorForView()); } else if (isActivity) { result.addMethod(createBindingConstructorForActivity()); } else if (isDialog) { result.addMethod(createBindingConstructorForDialog()); if (!constructorNeedsView()) { // Add a delegating constructor with a target type + view signature for reflective use. result.addMethod(createBindingViewDelegateConstructor()); result.addMethod(createBindingConstructor(sdk)); // 添加方法 if (hasViewBindings() || parentBinding == null) { result.addMethod(createBindingUnbindMethod(result)); return result.build();

ok,到这里编译过程就结束了,接下来看api层,看看Sample的MainActivity中的onCreate()方法是怎么使用ButterKnife的:

@Override protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.simple_activity);
    // 重点看这里
    ButterKnife.bind(this);
    // Contrived code to use the bound fields.
    title.setText("Butter Knife");
    subtitle.setText("Field and method binding for Android views.");
    footer.setText("by Jake Wharton");
    hello.setText("Say Hello");
    adapter = new SimpleAdapter(this);
    listOfThings.setAdapter(adapter);

调用bind方法,完成对MainActivity中的BindView注解的功能,那看一下ButterKnife.bind(this)方法:

* 11111111111111111111 @NonNull @UiThread public static Unbinder bind(@NonNull Activity target) { View sourceView = target.getWindow().getDecorView(); // 再看createBinding方法 return createBinding(target, sourceView); * 2222222222222222222 private static Unbinder createBinding(@NonNull Object target, @NonNull View source) { Class<?> targetClass = target.getClass(); //关键看这里 findBindingConstruc方法,去找target对应的生成类的构造函数 Constructor<? extends Unbinder> constructor = findBindingConstructorForClass(targetClass); if (constructor == null) { return Unbinder.EMPTY; //noinspection TryWithIdenticalCatches Resolves to API 19+ only type. try { // 反射创建指定的Class对象 return constructor.newInstance(target, source); } catch (IllegalAccessException e) { * 3333333333333333333 @Nullable @CheckResult @UiThread private static Constructor<? extends Unbinder> findBindingConstructorForClass(Class<?> cls) { // 从缓存获取,再进行一系列的验证操作 try { // 重点看这里,文件的命名规则是类名 + "_ViewBinding" // 我们之前demo的规则是 "$$Inject" Class<?> bindingClass = Class.forName(clsName + "_ViewBinding"); //noinspection unchecked bindingCtor = (Constructor<? extends Unbinder>) bindingClass.getConstructor(cls, View.class); if (debug) Log.d(TAG, "HIT: Loaded binding class and constructor."); } catch (ClassNotFoundException e) { // 加入到缓存区 BINDINGS.put(cls, bindingCtor); return bindingCtor;

运行一下sample,看看生成的文件:

由于篇幅问题,我把一些跟核心代码无关的都删掉了,大家可以去自己去下载看,经过三步,bind方法终于是弄清楚了,跟我们的demo设计思路大同小异,除了命名规则其他几乎是一样的。

到此为止BindView的分析就完整结束了。

今天我们分析了目前流行的注解框架 ButterKnife的实现源码,在核心的设计思路上跟我们之前的demo并无太大差别,同时我们看到了设计者在框架的封装设计,安全性验证等都做足了功夫。了解了ButterKnife,我们在使用它的时候就能够有底气,不再为app的运行效率而担忧。

虽然我们核心思想已经掌握了,但是源码还是要仔细的阅读体会,熟悉相关的api,感受大牛的设计思想,对于我们都是难得的学习机会。

  • 私信