前言
我們經(jīng)常使用的一些第三方框架,比如:butterknife,通過一行注解就可以實(shí)現(xiàn)View
的“自動(dòng)賦值”。
那么,這其中的原理是什么呢?
為了帶大家更好的深入了解,本文將打造一個(gè)簡(jiǎn)單的 Demo,來說明這其中的原理。
Demo 雖然簡(jiǎn)單,但是完全按照 butterknife 實(shí)現(xiàn)的方式和原理打造。
實(shí)現(xiàn)思路
我們先看 Demo 的效果:
public class MainActivity extends AppCompatActivity {
// 被注解的 View
@BindView(R.id.tv)
TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 為 tv 賦值
InjectHelper.inject(this);
tv.setText("I am injected");
}
}
代碼非常簡(jiǎn)單,分為兩步:
- 通過
@BindView(R.id.tv)
指定被注解 View 的 Id 值; -
InjectHelper.inject(this);
,具體為 tv 賦值的方法。
@BindView
注解沒什么好解釋的,我們重點(diǎn)看下 InjectHelper.inject(this);
的實(shí)現(xiàn):
public class InjectHelper {
public static void inject(Activity host) {
// 1、
String classFullName = host.getClass().getName() + "$$ViewInjector";
try {
// 2、
Class proxy = Class.forName(classFullName);
// 3、
Constructor constructor = proxy.getConstructor(host.getClass())
// 4、
constructor.newInstance(host);
} catch (Exception e) {
e.printStackTrace();
}
}
}
- 獲得 View 所在 Activity 的類路徑,然后拼接一個(gè)字符串“$$ViewInjector”。這個(gè)是編譯時(shí)動(dòng)態(tài)生成的 Class 的完整路徑,也就是我們需要實(shí)現(xiàn)的,同時(shí)也是最關(guān)鍵的部分;
- 根據(jù) Class 路徑,使用
Class.forName(classFullName)
生成 Class 對(duì)象; - 得到 Class 的構(gòu)造函數(shù) constructor 對(duì)象;
- 使用
constructor.newInstance(host)
new 出一個(gè)對(duì)象,這會(huì)執(zhí)行對(duì)象的構(gòu)造方法,方法內(nèi)部是我們?yōu)?MainActivity 的 tv 賦值的地方。
我們先看一個(gè)生成好的 “XXX$$ViewInjector” 示例:
public class MainActivity$$ViewInjector {
public MainActivity$$ViewInjector(MainActivity activity) {
activity.tv = (TextView)activity.findViewById(2131427422);
}
}
到這里,我們大概知道了最關(guān)鍵的地方,就是如何生成 “XXX$$ViewInjector” 這個(gè)類了。
APT 實(shí)現(xiàn)方案
APT 是一種處理注解的工具,它對(duì)源代碼文件進(jìn)行檢測(cè)找出其中的 Annotation,再根據(jù)注解自動(dòng)生成代碼。
實(shí)現(xiàn)方案,分為兩種:
- android-apt,個(gè)人開發(fā)者提供,現(xiàn)在已經(jīng)停止維護(hù),作者推薦大家使用官方提供的解決方案。
- Android Gradle 插件:annotationProcessor,由官方提供支持。
如何由 android-apt 切換到 annotationProcessor,可以參考這里。
annotationProcessor 配置起來比較簡(jiǎn)單,另外由于是官方支持的,所以我們選擇第二種方案。
實(shí)現(xiàn)步驟
第一步:定義注解 @BindView
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.CLASS)
public @interface BindView {
int value();
}
沒什么好解釋的~
第二步:實(shí)現(xiàn) AbstractProcessor
1、新建一個(gè) Java Library,引入兩個(gè)第三方庫:
dependencies {
// ...
compile 'com.google.auto.service:auto-service:1.0-rc2'
compile 'com.squareup:javapoet:1.7.0'
}
-
auto-service:Google 公司出品,用于自動(dòng)為 JAVA Processor 生成 META-INF 信息。
如果你定義了一個(gè) Processor:
package foo.bar; import javax.annotation.processing.Processor; @AutoService(Processor.class) final class MyProcessor implements Processor { // … }
auto-service 會(huì)在編譯目錄生成一個(gè)文件,路徑是:META-INF/services/javax.annotation.processing.Processor,文件內(nèi)容為:
foo.bar.MyProcessor
-
javapoet:大名鼎鼎的 squareup 公司出品,封裝了一套生成 .java 源文件的 API。
以 HelloWorld 類為例:
package com.example.helloworld; public final class HelloWorld { public static void main(String[] args) { System.out.println("Hello, JavaPoet!"); } }
上面的代碼就是使用javapoet用下面的代碼進(jìn)行生成的:
MethodSpec main = MethodSpec.methodBuilder("main") .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .returns(void.class) .addParameter(String[].class, "args") .addStatement("$T.out.println($S)", System.class, "Hello, JavaPoet!") .build(); TypeSpec helloWorld = TypeSpec.classBuilder("HelloWorld") .addModifiers(Modifier.PUBLIC, Modifier.FINAL) .addMethod(main) .build(); JavaFile javaFile = JavaFile.builder("com.example.helloworld", helloWorld) .build(); javaFile.writeTo(System.out);
2、繼承 AbstractProcessor,配置相關(guān)信息:
@AutoService(Processor.class)
@SupportedAnnotationTypes({"com.example.BindView"})
@SupportedSourceVersion(SourceVersion.RELEASE_7)
public class ViewInjectProcessor extends AbstractProcessor {
@Override
public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) {
//...
}
}
- @AutoService(Processor.class),生成 META-INF 信息;
- @SupportedAnnotationTypes({"com.example.BindView"}),聲明 Processor 處理的注解,注意這是一個(gè)數(shù)組,表示可以處理多個(gè)注解;
- @SupportedSourceVersion(SourceVersion.RELEASE_7),聲明支持的源碼版本
補(bǔ)充說明一下,@SupportedAnnotationTypes 和 @SupportedSourceVersion 必須聲明,否則會(huì)報(bào)錯(cuò)。具體原因看大家看一下源碼就明白了,這里不做過多解釋。
除了注解方式,你也可以通過重寫下面兩個(gè)函數(shù)實(shí)現(xiàn):
@AutoService(Processor.class)
public class ViewInjectProcessor extends AbstractProcessor {
@Override
public Set<String> getSupportedAnnotationTypes() {
Set<String> annotationTypes = new HashSet<>();
annotationTypes.add("com.example.BindView");
return annotationTypes;
}
@Override
public SourceVersion getSupportedSourceVersion() {
return SourceVersion.RELEASE_7;
}
}
3、實(shí)現(xiàn) AbstractProcessor 的 process()
方法:
@Override
public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) {
// 1、
collectInfo(roundEnvironment);
// 2、
writeToFile();
return true;
}
process()
方法的實(shí)現(xiàn),分為兩個(gè)步驟:
- 收集 Class 內(nèi)的所有被
@BindView
注解的成員變量; - 根據(jù)上一步收集的內(nèi)容,生成 .java 源文件。
為此,我們聲明了兩個(gè) Map,用于保存 collectInfo()
收集的相關(guān)信息,Map 的 key 為類的全路徑:
// 存放同一個(gè)Class下的所有注解信息
Map<String, List<VariableInfo>> classMap = new HashMap<>();
// 存放Class對(duì)應(yīng)的信息:TypeElement
Map<String, TypeElement> classTypeElement = new HashMap<>();
VariableInfo 是一個(gè)簡(jiǎn)單的類,用于保存被注解 View 對(duì)應(yīng)的一些信息:
public class VariableInfo {
// 被注解 View 的 Id 值
int viewId;
// 被注解 View 的信息:變量名稱、類型
VariableElement variableElement;
// ...
}
4、實(shí)現(xiàn) collectInfo()
方法:
void collectInfo(RoundEnvironment roundEnvironment) {
classMap.clear();
classTypeElement.clear();
Set<? extends Element> elements = roundEnvironment.getElementsAnnotatedWith(BindView.class);
for (Element element : elements) {
// 獲取 BindView 注解的值
int viewId = element.getAnnotation(BindView.class).value();
// 代表被注解的元素
VariableElement variableElement = (VariableElement) element;
// 備注解元素所在的Class
TypeElement typeElement = (TypeElement) variableElement.getEnclosingElement();
// Class的完整路徑
String classFullName = typeElement.getQualifiedName().toString();
// 收集Class中所有被注解的元素
List<VariableInfo> variableList = classMap.get(classFullName);
if (variableList == null) {
variableList = new ArrayList<>();
classMap.put(classFullName, variableList);
// 保存Class對(duì)應(yīng)要素(名稱、完整路徑等)
classTypeElement.put(classFullName, typeElement);
}
VariableInfo variableInfo = new VariableInfo();
variableInfo.setVariableElement(variableElement);
variableInfo.setViewId(viewId);
variableList.add(variableInfo);
}
}
代碼的注釋已經(jīng)很完整,這里不再說明了。
這里提一下 Element 這個(gè)元素,它的子類我們用到了以下兩個(gè):
Element
- VariableElement:代表變量
- TypeElement:代表 class
5、實(shí)現(xiàn) writeToFile()
方法:
void writeToFile() {
try {
for (String classFullName : classMap.keySet()) {
TypeElement typeElement = classTypeElement.get(classFullName);
// 使用構(gòu)造函數(shù)綁定數(shù)據(jù)
MethodSpec.Builder constructor = MethodSpec.constructorBuilder()
.addModifiers(Modifier.PUBLIC)
.addParameter(ParameterSpec.builder(TypeName.get(typeElement.asType()), "activity").build());
List<VariableInfo> variableList = classMap.get(classFullName);
for (VariableInfo variableInfo : variableList) {
VariableElement variableElement = variableInfo.getVariableElement();
// 變量名稱(比如:TextView tv 的 tv)
String variableName = variableElement.getSimpleName().toString();
// 變量類型的完整類路徑(比如:android.widget.TextView)
String variableFullName = variableElement.asType().toString();
// 在構(gòu)造方法中增加賦值語句,例如:activity.tv = (android.widget.TextView)activity.findViewById(215334);
constructor.addStatement("activity.$L=($L)activity.findViewById($L)", variableName, variableFullName, variableInfo.getViewId());
}
// 構(gòu)建Class
TypeSpec typeSpec = TypeSpec.classBuilder(typeElement.getSimpleName() + "$$ViewInjector")
.addModifiers(Modifier.PUBLIC)
.addMethod(constructor.build())
.build();
// 與目標(biāo)Class放在同一個(gè)包下,解決Class屬性的可訪問性
String packageFullName = elementUtils.getPackageOf(typeElement).getQualifiedName().toString();
JavaFile javaFile = JavaFile.builder(packageFullName, typeSpec)
.build();
// 生成class文件
javaFile.writeTo(filer);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
這段代碼主要就是通過 javapoet 來生成 .java 源文件,大家如果感覺陌生,建議先看一下 javapoet 的使用,參考文章: JavaPoet的基本使用。
當(dāng)然,你完全可以通過拼接字符串來生成 .java 源文件的內(nèi)容。
還記得文章開頭提到的 “XXX$$ViewInjector” 嗎?writeToFile()
方法,就是為了生成這個(gè) .java 源文件的。
第三步:使用 annotationProcessor
在 app 的 build.gradle 文件中,使用 APT:
dependencies {
// ...
annotationProcessor project(':lib-compiler')
}
lib-compiler:為第二步新建的 Java Library。
第四步:Activity 中使用 @BindView
文章開始已經(jīng)演示過相關(guān)代碼了,這里不再貼了。
一共分為以下兩步:
-
@BindView
注解相關(guān) View; - 調(diào)用
InjectHelper.inject(this)
方法。
然后,你嘗試去編譯項(xiàng)目,會(huì)發(fā)現(xiàn) APT 為我們自動(dòng)生成了 XXX$$ViewInjector.class 文件。
你可以在 app/build/intermediates/classes/debug(release、其他 buildType) 下對(duì)應(yīng)的包中找到。
APT 開啟 debug 模式
AS 中 debug Java 源代碼很簡(jiǎn)單,但是如果你想調(diào)試 APT 代碼(AbstractProcessor),就必須做一些配置了。
第一步:配置 gradle.properties 文件
首先找到本地電腦的 gradle home,它一般在當(dāng)前用戶的目錄下,比如我的 Mac 電腦位置在: ~/用戶名/.gradle。
打開(如果沒有,新建一個(gè))gradle.properties 文件,增加下面兩行:
org.gradle.daemon=true
org.gradle.jvmargs=-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005
第二步:增加 Remote 編譯選項(xiàng)
1、找到:Select Run/Debug Configration -> Edit Configrations...,如下圖
2、左側(cè)面板,點(diǎn)擊“+”,選擇 Remote,如下圖
3、隨便填入一個(gè)名字,比如 APT,點(diǎn)擊 Apply、Ok,使用默認(rèn)配置完成設(shè)置
4、切換到 APT,點(diǎn)擊 Debug 按鈕,建立到本地5005端口的連接
成功之后,會(huì)有如下提示
這樣,我們已經(jīng)可以開始調(diào)試 APT 代碼了。
第三步:開始調(diào)試
設(shè)置好斷點(diǎn),然后選擇 AS 菜單欄:Build -> Rebuild Project,
然后,開始調(diào)試你的 APT 代碼吧~
因?yàn)?AS 啟動(dòng)一個(gè)項(xiàng)目的時(shí)候,默認(rèn)也會(huì)去占用上面配置的 5005 端口。所以,你如果你發(fā)現(xiàn) AS 提示你端口被占用,請(qǐng)先殺掉本地占用 5005 端口的進(jìn)程。
另外,這一步使用 Rebuild Project 也是我嘗試多次后得出最靠譜的方案。網(wǎng)上有說
gradle clean assembleDebug
命令也可以開啟 debug APT,我這里發(fā)現(xiàn)不太穩(wěn)定,有時(shí)候不可以,不知道原因出在哪里,知道的同學(xué)麻煩告知下~
本文示例代碼:CompilerAnnotation
參考文章: