簡介
butterknife來自于 著名的大神JakeWharton,github 上是這么描述它的功能和原理的。
- 功能
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的原理,先來看它定義的所有注解如下圖:
這里我們來看常用的注解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原理。