做者: 張德帥, 時間: 2018.6.30 星期六 天氣晴html
一眨眼功夫又到週末,總以爲小日子過得不夠充實(實際上是王者榮耀很差玩了...)。java
不過我能夠跟Butterknife談情說愛(RTFSC:Read The Fucking Source Code),本篇文章即是「愛的結晶」 。android
Android大神JakeWharton的做品(其它還有OKHttp、Retrofit等)。Butterknife使用註解代替findViewById()等,可讀性高、優雅、開發效率提升等。這裏就再也不列舉Butterknife優勢,相信各位老司機早就精通Butterknife使用。本篇主要學習Butterknife核心源碼,萬丈高樓平地起,直接殺入源碼不免無頭蒼蠅,一臉懵逼,文章從如下幾個部分聊起(瞎扯)。git
(強行插入表情包)github
來不及解釋了 快上車 滴... 學生卡。Butterknife 基本使用姿式編程
一、在App build.gradle配置依賴緩存
dependencies {
implementation 'com.jakewharton:butterknife:8.8.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
}
複製代碼
二、在Activity使用bash
public class MainActivity extends AppCompatActivity {
@BindView(R.id.tv_name)
TextView tvName;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
}
}
複製代碼
上面看到使用很是簡單,幾個註解就搞定以前一大堆findViewById()等代碼,那麼它是怎麼作到的?答案是:butterknife會掃描這些自定義註解,根據註解信息生成Java文件,ButterKnife.bind(this)實際會執行自動生成的代碼。紅色框選部分文章後面會詳細分析,能夠了解到 在讀Butterknife源碼以前得先回顧Java基礎-註解。app
目錄:app\build\generated\source\apt\ (APT掃描解析 註解 生成的代碼)。 框架
註解能夠理解爲代碼的標識,不會對運行有直接影響。
Java內置幾個經常使用註解,這部分標識源碼,會被編譯器識別,提示錯誤等。
@Override 標記覆蓋方法
@Deprecated 標記爲過期
@SuppressWarnings 忽略警告
假設咱們要自定義一個註解,這時候就須要用元註解去聲明自定義註解,包括像註解做用域、生命週期等。
@Documented 能夠被javadoc文檔化。
@Target 註解用在哪
@Inherited
@Retention
使用元註解建立自定義註解
//直到運行時還保留註解
@Retention(RetentionPolicy.RUNTIME)
//做用域 類
@Target(ElementType.TYPE)
public @interface BindV {
int resId() default 0;
}
複製代碼
在代碼中定義了標識,如今想拿到這些信息,能夠經過反射、APT獲取註解的值。
經過反射解析註解(這裏也不闡述什麼是反射)
BindV.java 文件
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface BindV {
int resId() default 0;
}
複製代碼
MainActivity.java 文件
@BindV(resId = R.layout.activity_main)
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//這裏是舉個栗子反射當前類,設置佈局文件,固然在實際中這部分代碼多是通過封裝的。
Class clz = MainActivity.class;
BindV bindV = (BindV) clz.getAnnotation(BindV.class);//拿到佈局文件id
setContentView(bindV.resId());
}
}
複製代碼
APT(Annotation Processing Tool)註解處理器,是在編譯期間讀取註解,生成Java文件。反射解析註解是損耗性能的,接下來經過APT來生成java源碼,從而避免反射。
一、首先新建項目,再新建JavaLibrary。
JavaLibrary的Gradle配置,要想Java識別註解處理器,須要註冊到META-INF,這裏使用auto-service這個庫實現自動註冊。
apply plugin: 'java-library'
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.google.auto.service:auto-service:1.0-rc2'
}
sourceCompatibility = "1.7"
targetCompatibility = "1.7"
複製代碼
二、新建BindLayout註解
package com.example.abstractprocessorlib;
public @interface BindLayout {
int viewId();
}
複製代碼
三、新建AbstractProcessor子類
package com.example.abstractprocessorlib;
@AutoService(Processor.class)
public class MyProcessor extends AbstractProcessor {
private Types typesUtils;//類型工具類
private Elements elementsUtils;//節點工具類
private Filer filerUtils;//文件工具類
private Messager messager;//處理器消息輸出(注意它不是Log工具)
//init初始化方法,processingEnvironment會提供不少工具類,這裏獲取Types、Elements、Filer、Message經常使用工具類。
@Override
public synchronized void init(ProcessingEnvironment processingEnvironment) {
super.init(processingEnvironment);
typesUtils = processingEnvironment.getTypeUtils();
elementsUtils = processingEnvironment.getElementUtils();
filerUtils = processingEnvironment.getFiler();
messager = processingEnvironment.getMessager();
}
//這裏掃描、處理註解,生成Java文件。
@Override
public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) {
//拿到全部被BindLayout註解的節點
Set<? extends Element> elements = roundEnvironment.getElementsAnnotatedWith(BindLayout.class);
for (Element element : elements) {
//輸出警告信息
processingEnv.getMessager().printMessage(Diagnostic.Kind.WARNING, "element name:" + element.getSimpleName(), element);
//判斷是否 用在類上
if (element.getKind().isClass()) {
//新文件名 類名_Bind.java
String className = element.getSimpleName() + "_Bind";
try {
//拿到註解值
int viewId = element.getAnnotation(BindLayout.class).viewId();
//建立文件 包名com.example.processor.
JavaFileObject source = filerUtils.createSourceFile("com.example.processor." + className);
Writer writer = source.openWriter();
//文件內容
writer.write("package com.example.processor;\n" +
"\n" +
"import android.app.Activity;\n" +
"\n" +
"public class " + className + " { \n" +
"\n" +
" public static void init(Activity activity){\n" +
" activity.setContentView(" + viewId + ");\n" +
" }\n" +
"}");
writer.flush();
//完成寫入
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return false;
}
//要掃描哪些註解
@Override
public Set<String> getSupportedAnnotationTypes() {
Set<String> annotationSet = new HashSet<>();
annotationSet.add(BindLayout.class.getCanonicalName());
return annotationSet;
}
//支持的JDK版本,建議使用latestSupported()
@Override
public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latestSupported();
}
}
複製代碼
二、在App的Gradle文件 添加配置
dependencies {
annotationProcessor project(path: ':AbstractProcessorLib')
implementation project(path: ':AbstractProcessorLib')
}
複製代碼
三、在app\build\generated\source\apt\debug 目錄下,能夠看到APT 生成的文件。
能夠在Activity使用剛纔生成的文件
假設遇到這個錯誤,能夠參考修改Grandle配置
Gradle配置
一、JavaPoet
從上面APT能夠看到拼接Java文件是比較複雜的,好在Square開源了JavPoet這個庫,否則整個文件全靠字符串拼接... 有了這個庫生成代碼,就像寫詩同樣。修改剛纔process()方法
@Override
public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) {
Set<? extends Element> elements = roundEnvironment.getElementsAnnotatedWith(BindLayout.class);
for (Element element : elements) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.WARNING, "element name:" +element.getSimpleName(), element);
if (element.getKind().isClass()) {
String className = element.getSimpleName() + "_Bind";
try {
int viewId = element.getAnnotation(BindLayout.class).viewId();
//獲得android.app.Activity這個類
ClassName activityClass = ClassName.get("android.app", "Activity");
//建立一個方法
MethodSpec initMethod = MethodSpec.methodBuilder("init")
.addModifiers(Modifier.PUBLIC, Modifier.STATIC)//修飾符
.addParameter(activityClass, "activity")//參數
.returns(TypeName.VOID)//返回值
.addStatement("activity.setContentView(" + viewId + ");")//方法體
.build();
//建立一個類
TypeSpec typeSpec = TypeSpec.classBuilder(className)//類名
.addModifiers(Modifier.PUBLIC)//修飾符
.addMethod(initMethod)//將方法加入到這個類
.build();
//建立java文件,指定包名類
JavaFile javaFile = JavaFile.builder("com.example.processor", typeSpec)
.build();
javaFile.writeTo(filerUtils);
} catch (Exception e) {
e.printStackTrace();
}
}
}
return false;
}
複製代碼
先到gayhub 下載源碼,butterknife、butterknife-annotations、butterknife-compiler三個核心模塊,也是主要閱讀的部分。
一、首先來分析一下build\generated\source\apt**\MainActivity_ViewBinding.java 這個文件生成大概過程,以前咱們是用註解處理器生成代碼,在butterknife-compiler模塊的ButterKnifeProcessor.java類負責生成 ClassName_ViewBinding.java文件。 過程以下:
(爲了方便快速閱讀代碼,把註釋或代碼強壯性判斷移除)首先是init方法,沒有過多複雜的,主要是工具類獲取。
@Override
public synchronized void init(ProcessingEnvironment env) {
super.init(env);
elementUtils = env.getElementUtils();
typeUtils = env.getTypeUtils();
filer = env.getFiler();
trees = Trees.instance(processingEnv);
}
複製代碼
getSupportedSourceVersion、getSupportedAnnotationTypes方法。
@Override
public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latestSupported();
}
@Override
public Set<String> getSupportedAnnotationTypes() {
Set<String> types = new LinkedHashSet<>();
for (Class<? extends Annotation> annotation : getSupportedAnnotations()) {
types.add(annotation.getCanonicalName());
}
return types;
}
private Set<Class<? extends Annotation>> getSupportedAnnotations() {
Set<Class<? extends Annotation>> annotations = new LinkedHashSet<>();
annotations.add(BindAnim.class);
annotations.add(BindArray.class);
...
return annotations;
}
複製代碼
接下來重點是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;
}
複製代碼
分析findAndParseTargets(env)這行,找到這個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); } } 省略... 複製代碼
繼續往下找 parseBindView()方法
private void parseBindView(Element element, Map<TypeElement, BindingSet.Builder> builderMap,
Set<TypeElement> erasedTargetNames) {
//當前註解所在的類
TypeElement enclosingElement = (TypeElement) element.getEnclosingElement();
//校驗類、要綁定的字段 修飾符 private static,不能夠在Framework層使用已java. android.開始的包名
boolean hasError = isInaccessibleViaGeneratedCode(BindViews.class, "fields", element)
|| isBindingInWrongPackage(BindViews.class, element);
// 要綁定的字段是否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.
//保存View ID之間映射
int id = element.getAnnotation(BindView.class).value();
BindingSet.Builder builder = builderMap.get(enclosingElement);//從緩存取出來
Id resourceId = elementToId(element, BindView.class, id);
if (builder != null) {//說明以前被綁定過
String existingBindingName = builder.findExistingBindingName(resourceId);
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 {
//構建要綁定View的映射關係,繼續看getOrCreateBindingBuilder方法信息
builder = getOrCreateBindingBuilder(builderMap, enclosingElement);
}
String name = simpleName.toString();
TypeName type = TypeName.get(elementType);
boolean required = isFieldRequired(element);
//咱們Activity類有不少 BindView註解的控件,是以類包含字段,這裏的builder至關於類,判斷若是類存在就往裏加字段。
builder.addField(resourceId, new FieldViewBinding(name, type, required));
// Add the type-erased version to the valid binding targets set.
erasedTargetNames.add(enclosingElement);
}
//直接看newBuilder
private BindingSet.Builder getOrCreateBindingBuilder(
Map<TypeElement, BindingSet.Builder> builderMap, TypeElement enclosingElement) {
BindingSet.Builder builder = builderMap.get(enclosingElement);
if (builder == null) {
builder = BindingSet.newBuilder(enclosingElement);
builderMap.put(enclosingElement, builder);
}
return builder;
}
//至關於建立一個類,類名是一開始看到的 類名_ViewBinding
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");
boolean isFinal = enclosingElement.getModifiers().contains(Modifier.FINAL);
return new Builder(targetType, bindingClassName, isFinal, isView, isActivity, isDialog);
}
回到process方法,這行就是將剛掃描的信息寫入到文件
JavaFile javaFile = binding.brewJava(sdk, debuggable, useAndroidX);
複製代碼
至此咱們知道*_ViewBinding文件生成過程,接下來看怎麼使用,從Butterknife.bind()方法查看
public static Unbinder bind(@NonNull Activity target) {
View sourceView = target.getWindow().getDecorView();//拿到decorView
return createBinding(target, sourceView);
}
複製代碼
進入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
//拿到類_ViewBinding的構造方法
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);
}
}
複製代碼
繼續看findBindingConstructorForClass()方法,根據當前類先從緩存找構造方法,沒有的話根據類名_ViewBinding找到構造方法。
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 {
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;
}
複製代碼
//到這一步咱們清楚,是先生成文件,而後Butterknife.bind()方法關聯生成的文件並執行構造。接下來看看生成的文件構造作了什麼 //我在apt目錄下找到一個文件SimpleActivity_ViewBinding.java文件,代碼量多 我簡化一下,直接看findRequireViewAsType()方法。
@UiThread
public SimpleActivity_ViewBinding(SimpleActivity target) {
this(target, target.getWindow().getDecorView());
}
@UiThread
public SimpleActivity_ViewBinding(final SimpleActivity target, View source) {
this.target = target;
View view;
target.title = Utils.findRequiredViewAsType(source, R.id.title, "field 'title'", TextView.class);
}
//繼續看findRequiredView
public static <T> T findRequiredViewAsType(View source, @IdRes int id, String who,
Class<T> cls) {
View view = findRequiredView(source, id, who);
return castView(view, id, who, cls);
}
//findRequiredView()方法,能夠看到其實仍是使用findViewByID()查找View只不過是自動生成。
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.");
}
複製代碼
//以上就是Butterknife基本原理,第一部分apt掃描註解信息生成文件,第二部分Butterknife.bind方法找到對於文件,執行構造,並執行findView獲取view。
推薦一篇文章:Android主項目和Module中R類的區別 https://www.imooc.com/article/23756
最後:其實在MVVM、Kotlin等出來以後,Butterknife熱度慢慢降低,但這根本不影響咱們去了解 這如此優秀的框架。