1. 程式人生 > >Butterknife原始碼分析與原理簡述

Butterknife原始碼分析與原理簡述

一、背景

Butterknife 作為一款幾乎每一個Android開發都會用到的常用開源元件,可以繫結android檢視和事件回撥到欄位和方法,它通過使用註解處理並生成模版程式碼,為你繫結android檢視中到欄位和方法。如此有用到第三方開源元件,我們有必要去了解它到實現流程。

這裡寫圖片描述

二、原理解析

這裡我們來看常用的註解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;
  }

來看註釋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
  }

裡面可以看到實際上它是建立了一個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原理。