butterknife原始碼簡單分析&原理簡述

zyl409214686發表於2017-12-23

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原理。

相關文章