butterknife源码简单分析&原理简述

简介

butterknife来自于 著名的大神JakeWhartongithub 上是这么描述它的功能和原理的。

  • 功能

Bind Android views and callbacks to fields and methods.


绑定android视图和事件回调到字段和方法。

  • 原理

Field and method binding for Android views which uses annotation processing to generate boilerplate code for you.

通过使用注解处理并生成模板代码,为你绑定android视图中的字段和方法。

源码解读

工欲善其事,必先利其器。我们把butterknife 导入到insight.io中。
上面已经简述了butterknife的原理,先来看它定义的所有注解如下图:

注解.png

这里我们来看常用的注解BindView
@Retention(Class)表明@BindView采用的是编译时注解
@Target(FIELD)则表明它应用于成员变量

接下来我们写一个很简单的例子,后面将会用到此代码。

public class HelloActivity extends Activity {
    @BindView(R.id.tv_hello)
    TextView mHelloTv;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hello);
        ButterKnife.bind(this);
    }
}

butterknife的原理主要分为三个部分来介绍,主要为:注解生成模板代码分析、butterknife.bind()方法分析、生成的模板类代码分析。

  • 注解生成模板代码分析

butterknife注册的注解器为ButterKnifeProcessor,源码在在butterknife-compiler工程下

@AutoService(Processor.class)
public final class ButterKnifeProcessor extends AbstractProcessor {
  ...
  @Override public boolean process(Set<? extends TypeElement> elements, RoundEnvironment env) {
    Map<TypeElement, BindingSet> bindingMap = findAndParseTargets(env);//1
    for (Map.Entry<TypeElement, BindingSet> entry : bindingMap.entrySet()) {
      TypeElement typeElement = entry.getKey();
      BindingSet binding = entry.getValue();//8
      JavaFile javaFile = binding.brewJava(sdk, debuggable);
      try {
        javaFile.writeTo(filer);
      } catch (IOException e) {
        error(typeElement, "Unable to write binding for type %s: %s", typeElement, e.getMessage());
      }
    }
    return false;
  }
  ...
}

先来看注释1处调用的findAndParseTargets方法,顾名思义此方法为查找并解析目标注解,源码如下:

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); //2
      } catch (Exception e) {
        logParsingError(element, BindView.class, e);
      }
    }
    ...
    return bindingMap;
}

接着查看注释2处parseBindView方法:

  private void parseBindView(Element element, Map<TypeElement, BindingSet.Builder> builderMap,
      Set<TypeElement> erasedTargetNames) {
      TypeElement enclosingElement = (TypeElement) element.getEnclosingElement();
      ... //非本文重点略掉。此处主要为一些限定性验证,(如元素修饰符不能为private,static、元素包含类型不能为非Class类型、包名不能为java. android.等)。
      // Assemble information on the field.
      String name = element.getSimpleName().toString();
      int[] ids = element.getAnnotation(BindViews.class).value();
      BindingSet.Builder builder = getOrCreateBindingBuilder(builderMap, enclosingElement);//3
      builder.addFieldCollection(new FieldCollectionViewBinding(name, type, kind, idVars,   required));
}

来看注释3处,如下:

private BindingSet.Builder getOrCreateBindingBuilder(
      Map<TypeElement, BindingSet.Builder> builderMap, TypeElement enclosingElement) {
    BindingSet.Builder builder = builderMap.get(enclosingElement);
    if (builder == null) {
      builder = BindingSet.newBuilder(enclosingElement);//4
      builderMap.put(enclosingElement, builder);
    }
    return builder;
  }

顾名思义获取或创建BindingBuilder,从builderMap中获取BindingSet.Builder如果有则return, 如果没有则创建并放入Map缓存中。那么BindingSet.Builder存储的是什么的?接下来我们看注释4处builder对象的创建,如下:

static Builder newBuilder(TypeElement enclosingElement) {
    TypeMirror typeMirror = enclosingElement.asType();

    boolean isView = isSubtypeOfType(typeMirror, VIEW_TYPE);
    boolean isActivity = isSubtypeOfType(typeMirror, ACTIVITY_TYPE);
    boolean isDialog = isSubtypeOfType(typeMirror, DIALOG_TYPE);

    TypeName targetType = TypeName.get(typeMirror);
    if (targetType instanceof ParameterizedTypeName) {
      targetType = ((ParameterizedTypeName) targetType).rawType;
    }

    String packageName = getPackage(enclosingElement).getQualifiedName().toString();
    String className = enclosingElement.getQualifiedName().toString().substring(
        packageName.length() + 1).replace('.', '$');
    ClassName bindingClassName = ClassName.get(packageName, className + "_ViewBinding");//5

    boolean isFinal = enclosingElement.getModifiers().contains(Modifier.FINAL);
    return new Builder(targetType, bindingClassName, isFinal, isView, isActivity, isDialog);//6
  }

注释5ClassName bindingClassName = ClassName.get(packageName, className + "_ViewBinding");此bindingClassName就是要即将生成的模板类名称。
继续看注释6此处new 了 Builder类,根据名字我们可以看出这是一个创建者模式,来看看Builder类的build方法,如下:

 BindingSet build() {
      ImmutableList.Builder<ViewBinding> viewBindings = ImmutableList.builder();
      for (ViewBinding.Builder builder : viewIdMap.values()) {
        viewBindings.add(builder.build());
      }
      return new BindingSet(targetTypeName, bindingClassName, isFinal, isView, isActivity, isDialog,
          viewBindings.build(), collectionBindings.build(), resourceBindings.build(),
          parentBinding);//7
    }

注释7里面可以看到实际上它是创建了一个BindingSet对象。而这个BindingSet对象里面存储着生成类的名称以及注解类名称等。
接下来findAndParseTargets会把此BindingSet对象返回来,到ButterKnifeProcessor类的process方法, 重新贴一下代码:

@AutoService(Processor.class)
public final class ButterKnifeProcessor extends AbstractProcessor {
  ...
  @Override public boolean process(Set<? extends TypeElement> elements, RoundEnvironment env) {
    Map<TypeElement, BindingSet> bindingMap = findAndParseTargets(env);//1
    for (Map.Entry<TypeElement, BindingSet> entry : bindingMap.entrySet()) {
      TypeElement typeElement = entry.getKey();
      BindingSet binding = entry.getValue();//8
      JavaFile javaFile = binding.brewJava(sdk, debuggable);
      try {
        javaFile.writeTo(filer);
      } catch (IOException e) {
        error(typeElement, "Unable to write binding for type %s: %s", typeElement, e.getMessage());
      }
    }
    return false;
  }
  ...
}

注释8获取到了上面生成的BindingSet对象。

JavaFile javaFile = binding.brewJava(sdk, debuggable);
javaFile.writeTo(filer);

这两行代码为javapoet的范畴,其功能根据返回的binding对象配置信息生成我们需要用到的模板类代码,到此第一部分注解生成模板代码的源码就分析完了。

  • butterknife.bind()
    来看butterknife工程下butterknife包下的ButterKnife.java类bind方法。
public static Unbinder bind(@NonNull Activity target) {
    View sourceView = target.getWindow().getDecorView();
    return createBinding(target, sourceView);
  }

此方法有很多重载的方法, 这里我们只看绑定activity场景的重载方法。获取到activity中的decorview,将activity和decorview传入createBinding()方法。

private static Unbinder createBinding(@NonNull Object target, @NonNull View source) {
    Class<?> targetClass = target.getClass();
    if (debug) Log.d(TAG, "Looking up binding for " + targetClass.getName());
    Constructor<? extends Unbinder> constructor = findBindingConstructorForClass(targetClass);//1

    if (constructor == null) {
      return Unbinder.EMPTY;
    }

    //noinspection TryWithIdenticalCatches Resolves to API 19+ only type.
    try {
      return constructor.newInstance(target, source);//5
    ...
 }

注释1 进入findBindingConstructorForClass并传入了activity为参数,方法如下:

  private static Constructor<? extends Unbinder> findBindingConstructorForClass(Class<?> cls) {
    Constructor<? extends Unbinder> bindingCtor = BINDINGS.get(cls);//4
    if (bindingCtor != null) {
      if (debug) Log.d(TAG, "HIT: Cached in binding map.");
      return bindingCtor;
    }
    String clsName = cls.getName();
    if (clsName.startsWith("android.") || clsName.startsWith("java.")) {
      if (debug) Log.d(TAG, "MISS: Reached framework class. Abandoning search.");
      return null;
    }
    try {
      Class<?> bindingClass = cls.getClassLoader().loadClass(clsName + "_ViewBinding");//2
      //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) {
      if (debug) Log.d(TAG, "Not found. Trying superclass " + cls.getSuperclass().getName());
      bindingCtor = findBindingConstructorForClass(cls.getSuperclass());
    } catch (NoSuchMethodException e) {
      throw new RuntimeException("Unable to find binding constructor for " + clsName, e);
    }
    BINDINGS.put(cls, bindingCtor); //3
    return bindingCtor;
  }

先来看注释2处通过类加载器加载模板类,然后获取到它的构造方法,此处用到了反射会对性能有一定影响,为了优化性能看注解3会把构造方法加入到缓存map中,而注释4也就是方法开始的地方会对缓存做判断,如果有数据的话就直接返回了。createBinding ()方法 注释5处根据构造器创建xx_ViewBinding模板类对象,我们例子里面的模板类ming成为“HelloActivity_ViewBinding”。

  • 模板类代码分析
    接下来看HelloActivity_ViewBinding类,代码如下:
public class HelloActivity_ViewBinding implements Unbinder {
  private HelloActivity target;

  @UiThread
  public HelloActivity_ViewBinding(HelloActivity target) {
    this(target, target.getWindow().getDecorView());
  }

  @UiThread
  public HelloActivity_ViewBinding(HelloActivity target, View source) {
    this.target = target;

    target.mHelloTv = Utils.findRequiredViewAsType(source, R.id.tv_hello, "field 'mHelloTv'", TextView.class);//1
  }

  @Override
  @CallSuper
  public void unbind() {
    HelloActivity target = this.target;
    if (target == null) throw new IllegalStateException("Bindings already cleared.");
    this.target = null;

    target.mHelloTv = null;
  }
}

接下来进入注释1 findRequiredViewAsType方法

  public static <T> T findRequiredViewAsType(View source, @IdRes int id, String who,
      Class<T> cls) {
    View view = findRequiredView(source, id, who);//2
    return castView(view, id, who, cls); //3
  }

继续看注释2

public static View findRequiredView(View source, @IdRes int id, String who) {
    View view = source.findViewById(id);
    if (view != null) {
      return view;
    }
    String name = getResourceEntryName(source, id);
    ...
}

此处看到了我们熟悉的View view = source.findViewById(id);
注释3return castView(view, id, who, cls); 此处将view强制转型为cls类型。cls类型也就是下面的TextView.class。
target.mHelloTv = Utils.findRequiredViewAsType(source, R.id.tv_hello, "field 'mHelloTv'", TextView.class);此处的TextView.class。
将mHelloTv赋值给,target(也就是HelloActivity)。
至此我们的原理简单的分析完了。
哈哈,断断续续几个小时的时间又重新温习了一下butterknife原理。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,219评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,363评论 1 293
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,933评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,020评论 0 206
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,400评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,640评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,896评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,597评论 0 199
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,327评论 1 244
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,581评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,072评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,399评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,054评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,083评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,849评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,672评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,585评论 2 270

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,100评论 18 139
  • 博文出处:ButterKnife源码分析,欢迎大家关注我的博客,谢谢! 0x01 前言 在程序开发的过程中,总会有...
    俞其荣阅读 2,003评论 1 18
  • 0X0 前言 做过Android开发的猿类很多都知道ButterKnife这么个东西。这个库可以大大的简化我们的代...
    knightingal阅读 722评论 1 10
  • 清风无语,真好,你也在这里!
    决生采醉阅读 185评论 0 0
  • 把腿收一收 香 ...
    狗忧心忡忡阅读 202评论 0 1