一、本文需要解決的問(wèn)題
我研究Butterknife源碼的目的是為了解決以下幾個(gè)我在使用過(guò)程中所思考的問(wèn)題:
- 在很多文章中都提到Butterknife使用編譯時(shí)注解技術(shù)婿奔,什么是編譯時(shí)注解睦尽?
- 是完全不調(diào)用findViewById()等方法了嗎器净?
- 為什么綁定各種view時(shí)不能使用private修飾?
- 綁定監(jiān)聽(tīng)事件的時(shí)候方法命名有限制嗎当凡?
二掌动、初步分析
基于Butterknife 8.8.1版本。
為了更好地分析代碼宁玫,我寫(xiě)了一個(gè)demo:
MainActivity.java:
public class MainActivity extends Activity {
@BindView(R.id.text)
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
}
@OnClick(R.id.text)
public void textClick() {
Toast.makeText(MainActivity.this, "textview clicked", Toast.LENGTH_LONG);
}
}
我們從Butterknife.bind()方法,即方法入口開(kāi)始分析:
ButterKnife#bind():
@NonNull @UiThread
public static Unbinder bind(@NonNull Activity target) {
View sourceView = target.getWindow().getDecorView();
return createBinding(target, sourceView);
}
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());
// 8躺埂E繁瘛!
Constructor<? extends Unbinder> constructor = findBindingConstructorForClass(targetClass);
if (constructor == null) {
return Unbinder.EMPTY;
}
//noinspection TryWithIdenticalCatches Resolves to API 19+ only type.
try {
return constructor.newInstance(target, source);
} catch (IllegalAccessException e) {
throw new RuntimeException("Unable to invoke " + constructor, e);
} catch (InstantiationException e) {
throw new RuntimeException("Unable to invoke " + constructor, e);
} catch (InvocationTargetException e) {
Throwable cause = e.getCause();
if (cause instanceof RuntimeException) {
throw (RuntimeException) cause;
}
if (cause instanceof Error) {
throw (Error) cause;
}
throw new RuntimeException("Unable to create binding instance.", cause);
}
}
@Nullable @CheckResult @UiThread
private static Constructor<? extends Unbinder> findBindingConstructorForClass(Class<?> cls) {
Constructor<? extends Unbinder> bindingCtor = BINDINGS.get(cls);
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 {
// 3自蕖7鹨础!
Class<?> bindingClass = cls.getClassLoader().loadClass(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) {
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);
return bindingCtor;
}
代碼還是比較清晰的涌庭,bind()方法的流程:
- 首先獲取當(dāng)前activity的sourceView芥被,其實(shí)就是獲取Activity的DecorView,DecorView是整個(gè)ViewTree的最頂層View坐榆,包含標(biāo)題view和內(nèi)容view這兩個(gè)子元素拴魄。我們一直調(diào)用的setContentView()方法其實(shí)就是往內(nèi)容view中添加view元素。
- 然后調(diào)用createBinding() --> findBindingConstructorForClass()席镀,重點(diǎn)是
Class<?> bindingClass = cls.getClassLoader().loadClass(clsName + "_ViewBinding");
bindingCtor = (Constructor<? extends Unbinder>) bindingClass.getConstructor(cls, View.class);
BINDINGS.put(cls, bindingCtor);
按照所寫(xiě)的代碼匹中,這里會(huì)加載一個(gè)MainActivity_ViewBinding類(lèi),然后獲取這個(gè)類(lèi)里面的雙參數(shù)(Activity豪诲, View)構(gòu)造方法顶捷,最后放在BINDINGS里面,它是一個(gè)map屎篱,主要作用是緩存服赎。在下次使用的時(shí)候葵蒂,就可以從緩存中獲取到:
Constructor<? extends Unbinder> bindingCtor = BINDINGS.get(cls);
if (bindingCtor != null) {
if (debug) Log.d(TAG, "HIT: Cached in binding map.");
return bindingCtor;
}
三、關(guān)于編譯時(shí)注解
在上面分析過(guò)程中重虑,我們知道最后我們會(huì)去加載一個(gè)MainActivity_ViewBinding類(lèi)践付,而這個(gè)類(lèi)并不是我們自己編寫(xiě)的,而是通過(guò)編譯時(shí)注解(APT - Annotation Processing Tool)的技術(shù)生成的嚎尤。
這一節(jié)將會(huì)介紹一下這個(gè)技術(shù)荔仁。
1、什么是注解
注解其實(shí)很常見(jiàn)芽死,比如說(shuō)Activity自動(dòng)生成的onCreate()方法上面就有一個(gè)@Override注解
- 注解的概念:
能夠添加到 Java 源代碼的語(yǔ)法元數(shù)據(jù)乏梁。類(lèi)、方法关贵、變量遇骑、參數(shù)、包都可以被注解揖曾,可用來(lái)將信息元數(shù)據(jù)與程序元素進(jìn)行關(guān)聯(lián)落萎。 - 注解的分類(lèi):
- 標(biāo)準(zhǔn)注解,如Override炭剪, Deprecated练链,SuppressWarnings等
- 元注解,如@Retention, @Target, @Inherited, @Documented奴拦。當(dāng)我們要自定義注解時(shí)媒鼓,需要使用它們
- 自定義注解,表示自己根據(jù)需要定義的 Annotation
- 注解的作用:
- 標(biāo)記错妖,用于告訴編譯器一些信息
- 編譯時(shí)動(dòng)態(tài)處理绿鸣,如動(dòng)態(tài)生成java代碼
- 運(yùn)行時(shí)動(dòng)態(tài)處理,如得到注解信息
2暂氯、運(yùn)行時(shí)注解 vs 編譯時(shí)注解
一般有些人提到注解潮模,普遍就會(huì)覺(jué)得性能低下。但是真正使用注解的開(kāi)源框架卻很多例如ButterKnife痴施,Retrofit等等擎厢。所以注解是好是壞呢?
首先晾剖,并不是注解就等于性能差锉矢。更確切的說(shuō)是運(yùn)行時(shí)注解這種方式,由于它的原理是java反射機(jī)制齿尽,所以的確會(huì)造成較為嚴(yán)重的性能問(wèn)題沽损。
但是像Butterknife這個(gè)框架,它使用的技術(shù)是編譯時(shí)注解循头,它不會(huì)影響app實(shí)際運(yùn)行的性能(影響的應(yīng)該是編譯時(shí)的效率)绵估。
一句話總結(jié):
- 運(yùn)行時(shí)注解就是在應(yīng)用運(yùn)行的過(guò)程中炎疆,動(dòng)態(tài)地獲取相關(guān)類(lèi),方法国裳,參數(shù)等信息形入,由于使用java反射機(jī)制,性能會(huì)有問(wèn)題缝左;
- 編譯時(shí)注解由于是在代碼編譯過(guò)程中對(duì)注解進(jìn)行處理亿遂,通過(guò)注解獲取相關(guān)類(lèi),方法渺杉,參數(shù)等信息蛇数,然后在項(xiàng)目中生成代碼,運(yùn)行時(shí)調(diào)用是越,其實(shí)和直接運(yùn)行手寫(xiě)代碼沒(méi)有任何區(qū)別耳舅,也就沒(méi)有性能問(wèn)題了。
這樣我們就解決了第一個(gè)問(wèn)題倚评。
3浦徊、如何使用編譯時(shí)注解技術(shù)
這里要借助到一個(gè)類(lèi):AbstractProcessor
public class TestProcessor extends AbstractProcessor
{
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv)
{
// TODO Auto-generated method stub
return false;
}
}
重點(diǎn)是process()方法,它相當(dāng)于每個(gè)處理器的主函數(shù)main()天梧,可以在這里寫(xiě)相關(guān)的掃描和處理注解的代碼盔性,他會(huì)幫助生成相關(guān)的Java文件。后面我們可以具體看一下Butterknife中的使用呢岗。
四纯出、進(jìn)一步分析MainActivity_ViewBinding
我們了解了編譯時(shí)注解的基本概念之后,我們先看一下MainActivity_ViewBinding類(lèi)具體實(shí)現(xiàn)了什么敷燎。
在編寫(xiě)完demo之后,需要先build一下項(xiàng)目箩言,之后可以在build/generated/source/apt/debug/包名/下面找到這個(gè)類(lèi)硬贯,如圖所示:
接上面的分析,到最后會(huì)通過(guò)反射的方式去調(diào)用MainActivity_ViewBinding的構(gòu)造方法陨收。我們直接看這個(gè)類(lèi)的構(gòu)造方法:
@UiThread
public MainActivity_ViewBinding(final MainActivity target, View source) {
this.target = target;
View view;
// 1
view = Utils.findRequiredView(source, R.id.text, "field 'textView' and method 'textClick'");
// 2
target.textView = Utils.castView(view, R.id.text, "field 'textView'", TextView.class);
// 3
view2131165290 = view;
view.setOnClickListener(new DebouncingOnClickListener() {
@Override
public void doClick(View p0) {
target.textClick();
}
});
}
1饭豹、findRequiredView()
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);
throw new IllegalStateException("Required view '"
+ name
+ "' with ID "
+ id
+ " for "
+ who
+ " was not found. If this view is optional add '@Nullable' (fields) or '@Optional'"
+ " (methods) annotation.");
}
看到這里我們已經(jīng)解決了第二個(gè)問(wèn)題:到最后還是會(huì)調(diào)用findViewById()方法,并沒(méi)有完全舍棄這個(gè)方法务漩,這里的source代表著在上面代碼中傳入的MainActivity的DecorView拄衰。大家可以嘗試一下將Activity轉(zhuǎn)化為Fragment的情況~
2、Util.castView
在這里饵骨,我們解決了第三個(gè)問(wèn)題翘悉,綁定各種view時(shí)不能使用private修飾,而是需要用public或default去修飾居触,因?yàn)槿绻捎胮rivate修飾的話妖混,將無(wú)法通過(guò)對(duì)象.成員變量方式獲取到我們需要綁定的View老赤。
Util#castView():
public static <T> T castView(View view, @IdRes int id, String who, Class<T> cls) {
try {
return cls.cast(view);
} catch (ClassCastException e) {
String name = getResourceEntryName(view, id);
throw new IllegalStateException("View '"
+ name
+ "' with ID "
+ id
+ " for "
+ who
+ " was of the wrong type. See cause for more info.", e);
}
}
這里直接調(diào)用Class.cast強(qiáng)制轉(zhuǎn)換類(lèi)型,將View轉(zhuǎn)化為我們需要的view(TextView)制市。
3抬旺、
view2131165290 = view;
view.setOnClickListener(new DebouncingOnClickListener() {
@Override
public void doClick(View p0) {
target.textClick();
}
});
這里會(huì)生成一個(gè)成員變量來(lái)保存我們需要綁定的View,重點(diǎn)是下面它會(huì)調(diào)用setOnClickListener()方法祥楣,傳入的是DebouncingOnClickListener:
/**
* A {@linkplain View.OnClickListener click listener} that debounces multiple clicks posted in the
* same frame. A click on one button disables all buttons for that frame.
*/
public abstract class DebouncingOnClickListener implements View.OnClickListener {
static boolean enabled = true;
private static final Runnable ENABLE_AGAIN = new Runnable() {
@Override public void run() {
enabled = true;
}
};
@Override
public final void onClick(View v) {
if (enabled) {
enabled = false;
v.post(ENABLE_AGAIN);
doClick(v);
}
}
public abstract void doClick(View v);
}
這個(gè)DebouncingOnClickListener是View.OnClickListener的一個(gè)子類(lèi)开财,作用是防止一定時(shí)間內(nèi)對(duì)view的多次點(diǎn)擊,即防止快速點(diǎn)擊控件所帶來(lái)的一些不可預(yù)料的錯(cuò)誤误褪。個(gè)人認(rèn)為這個(gè)類(lèi)寫(xiě)的非常巧妙责鳍,既完美解決了問(wèn)題,又寫(xiě)的十分優(yōu)雅振坚,一點(diǎn)都不臃腫薇搁。
這里抽象了doClick()方法,實(shí)現(xiàn)代碼中是直接調(diào)用了target.textClick()渡八,這里解決了第四個(gè)問(wèn)題:綁定監(jiān)聽(tīng)事件的時(shí)候方法命名是沒(méi)有限制的啃洋,不一定需要嚴(yán)格命名為onClick,也不一定需要傳入View參數(shù)屎鳍。
五宏娄、MainActivity_ViewBinding的生成
上文提到,MainActivity_ViewBinding類(lèi)是通過(guò)編譯時(shí)注解技術(shù)生成的逮壁,我們找到Butterknife相關(guān)的繼承于AbstractProcessor的類(lèi)孵坚,ButterKnifeProcessor,我們直接看process()方法:
public final class ButterKnifeProcessor extends AbstractProcessor {
@Override
public boolean process(Set<? extends TypeElement> elements, RoundEnvironment env) {
// 1
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, 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()
這個(gè)方法的作用是處理所有的@BindXX注解卖宠,我們直接看處理@BindView的部分:
private Map<TypeElement, BindingSet> findAndParseTargets(RoundEnvironment 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);
}
}
// 省略代碼
}
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.
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));
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;
}
} else {
builder = getOrCreateBindingBuilder(builderMap, enclosingElement);
}
String name = simpleName.toString();
TypeName type = TypeName.get(elementType);
boolean required = isFieldRequired(element);
builder.addField(getId(qualifiedId), new FieldViewBinding(name, type, required));
// Add the type-erased version to the valid binding targets set.
erasedTargetNames.add(enclosingElement);
}
代碼邏輯是處理獲取相關(guān)注解的信息,比如綁定的資源id等等忧饭,然后通過(guò)獲取BindingSet.Builder類(lèi)的實(shí)例來(lái)創(chuàng)建一一對(duì)應(yīng)的關(guān)系扛伍,這里有一個(gè)判斷,如果builderMap存在相應(yīng)實(shí)例則直接取出builder词裤,否則通過(guò)getOrCreateBindingBuilder()方法生成一個(gè)新的builder刺洒,最后調(diào)用builder.addField()方法。
后續(xù)的話返回到findAndParseTargets()方法的最后一部分:
private Map<TypeElement, BindingSet> findAndParseTargets(RoundEnvironment env) {
// bindView()
// Associate superclass binders with their subclass binders. This is a queue-based tree walk
// which starts at the roots (superclasses) and walks to the leafs (subclasses).
Deque<Map.Entry<TypeElement, BindingSet.Builder>> entries =
new ArrayDeque<>(builderMap.entrySet());
Map<TypeElement, BindingSet> bindingMap = new LinkedHashMap<>();
while (!entries.isEmpty()) {
Map.Entry<TypeElement, BindingSet.Builder> entry = entries.removeFirst();
TypeElement type = entry.getKey();
BindingSet.Builder builder = entry.getValue();
TypeElement parentType = findParentType(type, erasedTargetNames);
if (parentType == null) {
bindingMap.put(type, builder.build());
} else {
BindingSet parentBinding = bindingMap.get(parentType);
if (parentBinding != null) {
builder.setParent(parentBinding);
bindingMap.put(type, builder.build());
} else {
// Has a superclass binding but we haven't built it yet. Re-enqueue for later.
entries.addLast(entry);
}
}
}
return bindingMap;
}
這里會(huì)生成一個(gè)bindingMap吼砂,key為T(mén)ypeElement逆航,代表注解元素類(lèi)型,value為BindSet類(lèi)渔肩,通過(guò)上述的builder.build()生成因俐,BindingSet類(lèi)中存儲(chǔ)了很多信息,例如綁定view的類(lèi)型,生成類(lèi)的className等等女揭,方便我們后續(xù)生成java文件蚤假。最后回到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, debuggable);
try {
javaFile.writeTo(filer);
} catch (IOException e) {
error(typeElement, "Unable to write binding for type %s: %s", typeElement, e.getMessage());
}
}
return false;
}
最后通過(guò)brewJava()方法生成java代碼。
這里使用到的是javapoet吧兔。javapoet是一個(gè)開(kāi)源庫(kù)磷仰,通過(guò)處理相應(yīng)注解來(lái)生成最后的java文件,這里是項(xiàng)目地址傳送門(mén)境蔼,具體技術(shù)不再分析灶平。
這篇文章會(huì)同步到我的個(gè)人日志,如有問(wèn)題箍土,請(qǐng)大家踴躍提出逢享,謝謝大家!