編輯:關於 Android 程式設計
在 Android 這片廣闊天地裡,Square 公司可謂藏龍門虎,而 Jake Wharton 更是其中的佼佼者。okhttp、leakcanary、retrofit、butterknife 等流行開源庫都出自他手,極大地提升了 Android 開發的效率與代碼的鬆耦合程度。下面就一起走進 ButterKnife 的源碼世界。
本系列文章對 ButterKnife 源碼進行分析,涉及細節較多但覆蓋面廣,一次看不懂也沒關係,慢慢來即可。文末會給出一個基於原理的 demo,重點在於思想。

本文以 8.4.0 版本為分析對象。下載源碼後可以看到結構劃分得很清晰:
butterknife:供 Android 使用的 API(android library);butterknife-annotations:使用時的注解(java library);butterknife-compiler:編譯時用到的注解處理器(java library);butterknife-gradle-plugin:輔助生成代碼的 gradle 插件;butterknife-integration-test:測試用例;butterknife-lint:lint 檢查;sample:demo。

接下來重點分析 butterknife-compiler 與 butterknife 兩個模塊。先看一眼原理圖:


以官方 demo 的 SimpleActivity 為例,編譯後會生成 SimpleActivity_ViewBinding,路徑如下:

內容如下:
// Generated code from Butter Knife. Do not modify! package com.example.butterknife.library; import butterknife.Unbinder; import butterknife.internal.DebouncingOnClickListener; import butterknife.internal.Utils; public class SimpleActivity_ViewBindingimplements Unbinder { protected T target; private View view2130968578; private View view2130968579; @UiThread public SimpleActivity_ViewBinding(final T target, View source) { this.target = target; View view; target.title = Utils.findRequiredViewAsType(source, R.id.title, "field 'title'", TextView.class); target.subtitle = Utils.findRequiredViewAsType(source, R.id.subtitle, "field 'subtitle'", TextView.class); view = Utils.findRequiredView(source, R.id.hello, "field 'hello', method 'sayHello', and method 'sayGetOffMe'"); target.hello = Utils.castView(view, R.id.hello, "field 'hello'", Button.class); view.setOnClickListener(new DebouncingOnClickListener() { @Override public void doClick(View p0) { target.sayHello(); } }); view.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View p0) { return target.sayGetOffMe(); } }); } @Override @CallSuper public void unbind() { T target = this.target; if (target == null) throw new IllegalStateException("Bindings already cleared."); target.title = null; target.subtitle = null; target.hello = null; view2130968578.setOnClickListener(null); view2130968578.setOnLongClickListener(null); view2130968578 = null; this.target = null; } }
雖然是自動生成的代碼,但可看出它的規律:在構造函數中 findViewById,在 unbind 中置 null,以便 GC 在合適時機回收內存。
在 Java 代碼編譯時期,javac 會調用注解處理器進行處理。我們可以定義自己的處理器:它以 Java 源碼(或字節碼)為輸入,生成一些文件(通常是 .java)作為輸出,這些生成的文件會與手寫源碼一樣被 javac 編譯。
自定義處理器都繼承自 AbstractProcessor,前幾個方法是固定寫法,核心在 process:
public class MyProcessor extends AbstractProcessor { @Override public SourceVersion getSupportedSourceVersion() { return SourceVersion.latestSupported(); } @Override public synchronized void init(ProcessingEnvironment processingEnv) { super.init(processingEnv); } @Override public Set getSupportedAnnotationTypes() { Set annotataions = new LinkedHashSet(); annotataions.add("com.example.MyAnnotation"); return annotataions; } @Override public boolean process(Set annoations, RoundEnvironment env) { return false; } } 要讓 javac 調用你的處理器,需先注冊。Google 提供了 auto-service 庫,一個注解即可搞定:
compile 'com.google.auto.service:auto-service:1.0-rc2'
@AutoService(Processor.class) public class BindViewProcessor extends AbstractProcessor { }Elements:處理 Element 的工具類;Types:處理 TypeMirror 的工具類;Filer:用於創建 .java 文件。
先看 ButterKnifeProcessor 的 init 方法,它獲取各類輔助工具:
private Filer mFiler; private Elements mElementUtils; private Messager mMessager; @Override public synchronized void init(ProcessingEnvironment env) { super.init(env); elementUtils = env.getElementUtils(); typeUtils = env.getTypeUtils(); filer = env.getFiler(); try { trees = Trees.instance(processingEnv); } catch (IllegalArgumentException ignored) { } }getSupportedSourceVersion() 返回 SourceVersion.latestSupported(),表明使用最新 Java 版本。核心的 process 方法則是兩步走:先 findAndParseTargets 查找並解析所有注解,形成 BindingClass 集合;再遍歷該集合,調用 brewJava 生成 java 文件。
@Override public boolean process(Set elements, RoundEnvironment env) { Map targetClassMap = findAndParseTargets(env); for (Map.Entry entry : targetClassMap.entrySet()) { TypeElement typeElement = entry.getKey(); BindingClass bindingClass = entry.getValue(); JavaFile javaFile = bindingClass.brewJava(); try { javaFile.writeTo(filer); } catch (IOException e) { error(typeElement, "Unable to write binding for type %s: %s", typeElement, e.getMessage()); } } return true; } 參數 RoundEnvironment 是注解處理框架中的工具類,用於查詢注解信息。findAndParseTargets 內部創建了一個 LinkedHashMap 以保證順序,然後逐一解析各類注解,這裡以代表性的 @BindView 為例,其餘大同小異。
理解源碼前需先了解 Element。官方注釋說它代表諸如包、類、方法之類的程序元素,是靜態的、語言級別的結構。源碼中每一部分都是某個特定類型的 Element:
public class ClassA { // TypeElement private int var_0; // VariableElement public ClassA() {} // ExecuteableElement public void setA(int newA) { } }可見類為 TypeElement,變量為 VariableElement,方法為 ExecuteableElement,它們都是 Element 的子類。Elements 代表源代碼,TypeElement 代表元素類型,但 TypeElement 並不包含類的具體信息(如父類),這些需通過 TypeMirror 獲取,可用 element.asType() 得到。
繼續看解析 @BindView 的 parseBindView 方法,其基本流程分五步:
private void parseBindView(Element element, MaptargetClassMap, Set erasedTargetNames) { TypeElement enclosingElement = (TypeElement) element.getEnclosingElement(); // 1. 檢查合法性 boolean hasError = isInaccessibleViaGeneratedCode(BindView.class, "fields", element) || isBindingInWrongPackage(BindView.class, element); // 2. 獲取 id 值 int id = element.getAnnotation(BindView.class).value(); // 3. 獲取或創建 BindingClass BindingClass bindingClass = targetClassMap.get(enclosingElement); if (bindingClass != null) { // 校驗重複綁定 } else { bindingClass = getOrCreateTargetClass(targetClassMap, enclosingElement); } // 4. 生成 FieldViewBinding 實體 String name = element.getSimpleName().toString(); TypeName type = TypeName.get(elementType); FieldViewBinding binding = new FieldViewBinding(name, type, required); // 5. 加入集合 bindingClass.addField(getId(id), binding); erasedTargetNames.add(enclosingElement); }
第一步合法性檢查,isInaccessibleViaGeneratedCode 會判斷:字段不能是 private 或 static,必須包含在某個類中,且所處類不能是 private。也就是說,使用 @BindView 時,所屬類可以是默認或 public,字段同理。
private boolean isInaccessibleViaGeneratedCode(Class annotationClass, String targetThing, Element element) { boolean hasError = false; TypeElement enclosingElement = (TypeElement) element.getEnclosingElement(); Set modifiers = element.getModifiers(); if (modifiers.contains(PRIVATE) || modifiers.contains(STATIC)) { error(element, "@%s %s must not be private or static. (%s.%s)", annotationClass.getSimpleName(), targetThing, enclosingElement.getQualifiedName(), element.getSimpleName()); hasError = true; } if (enclosingElement.getKind() != CLASS) { error(enclosingElement, "@%s %s may only be contained in classes.", annotationClass.getSimpleName(), targetThing); hasError = true; } if (enclosingElement.getModifiers().contains(PRIVATE)) { error(enclosingElement, "@%s %s may not be contained in private classes.", annotationClass.getSimpleName(), targetThing); hasError = true; } return hasError; } 另一個 isBindingInWrongPackage 則檢查包名,若以 android. 或 java. 開頭會拋出異常,避免在框架源碼包中使用。
需要說明的是,在處理器中拋異常不像普通 Java 代碼那樣直接 throw,而是借助 Messager 這個輔助類,以 Kind.ERROR 等級別輸出更友好的提示:
private void error(Element element, String message, Object... args) { printMessage(Kind.ERROR, element, message, args); } private void printMessage(Kind kind, Element element, String message, Object[] args) { if (args.length > 0) { message = String.format(message, args); } processingEnv.getMessager().printMessage(kind, message, element); }合法性檢查完成後,若 hasError 為 true 就直接返回,後續再獲取 id、創建 BindingClass、生成 FieldViewBinding 並加入集合。這些內容為理解源碼打下了基礎。

下一篇我們接著往下分析。
自定義控件之美:陰影與五種漸變效果全解析
一、陰影 Paint 類定義了一個名為 setShadowLayer 的方法: public void setShadowLayer(float radius, floa
從零實現下拉刷新:Android RefreshLayout 自定義手勢佈局全解析
專案裡需要下拉刷新功能,但目標 View 並不是 ListView 這類現成控件,而是普通 ViewGroup,需要自己實現。網上翻了半天沒找到特別合適、又看得懂的方案,
改寫 aapt 原始碼:自訂 Android 編譯後的資源 ID(0x02~0x7E 任你挑)
一、技術準備 今天來動手改一改 Android 編譯過程中的資源 ID。要講這件事,得先理解 Android 資源在編譯後的結構。 資源編譯完成後會產生一個 R 檔案,所
自製仿 MIUI 風格 ViewPagerIndicator:Tab 與頁面滑動聯動的完整實作
一、要做什麼 做過 Tab 切換的人大概都用過 TabPageIndicator,許多知名 App 也採用這個開源指示器。但你有沒有想過自己動手做一個?究竟有多複雜?這篇