Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 註解原理與主流註解框架解析:ButterKnife 與 EventBus 的差異

編輯:關於 Android 程式設計

註解是 Android 開發中降低樣板程式碼的關鍵手段。要真正理解 ButterKnife、EventBus、Dagger 這些框架為什麼效能差異那麼大,得先分清「執行期註解」與「編譯期註解」這兩條完全不同的技術路線。

一、註解的基本介紹

定義:註解是可以附加到 Java 原始碼中的語法中繼資料。類別、方法、變數、參數、套件都能被標註,用來把中繼資料與程式元素關聯起來。最常見的例子莫過於 @Override 與 @Deprecated。

元註解

元註解是「用來描述註解」的基本註解,所有自訂註解都離不開它。共四個:

@Retention — 保留方式

SOURCE:只保留在原始碼中,不寫入 class 檔,也不載入虛擬機。
CLASS:保留在原始碼與 class 檔中,但不載入虛擬機。
RUNTIME:保留在原始碼、class 檔中,最終載入虛擬機。

兩條路線的實質差別就在這裡:

  • 執行期註解(RUNTIME):執行時以反射動態取得對象、屬性、方法。這類框架(典型如 IOC 容器)彈性最高,但要付出反射查找的效能代價。
  • 編譯期註解(CLASS/SOURCE):編譯過程中依註解執行額外處理。ButterKnife 就是代表——它在編譯時依註解自動產生輔助類別。要玩這一套,需要引入 apt(或升級後的 annotation processing),寫一個繼承 AbstractProcessor 的類別並改寫 process(),在其中把註解資訊轉譯成你要的程式碼。

@Target — 作用範圍

ElementType.FIELD:變數
ElementType.METHOD:方法
ElementType.PARAMETER:參數
ElementType.CONSTRUCTOR:建構子
ElementType.LOCAL_VARIABLE:區域變數
ElementType.PACKAGE:套件

@Inherited

是否可被繼承,預設 false。

@Documented

是否收錄進 Javadoc 文件。

Java 內建的常用註解

  • @Override:標示該方法改寫自父類。編譯時會檢查,若父類中並無此方法則報錯。
  • @Deprecated:標示該方法已不建議使用,代表它有風險或已有更好的替代。
  • @SuppressWarnings:編譯時忽略指定的警告類型,例如版本檢查。

二、動手寫一個註解

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface TestAnnotation {
    String name() default "";
    int id() default 0;
}

關鍵字是 @interface。上方標註的元註解表明:這個註解只能修飾方法,且會保留到執行期。內部宣告的則是它擁有的屬性,都帶了預設值。

使用時在方法上標註並給值:

@TestAnnotation(name = "android", id = 1)
private void testAnno() { }

再透過反射把它讀出來:

private void outputAnnoDetail(Class clazz) {
    Method[] methods = clazz.getDeclaredMethods();
    for (Method method : methods) {
        TestAnnotation testAnnotation = method.getAnnotation(TestAnnotation.class);
        if (testAnnotation != null) {
            Log.d("annotation", "name------>" + testAnnotation.name()
                    + "------>id------>" + testAnnotation.id());
        }
    }
}

輸出:

name------>android------>id------>1

這是一個執行期註解。歸根結底,註解的作用就是標記一個可被識別的作用域,讓別人在執行期以反射讀取,或在編譯期由編譯器/註解處理器解析。

三、Android 主流註解框架

ButterKnife:編譯期註解的代表

ButterKnife 主要負責綁定 View 與其監聽事件。看它的 @BindView:

@Retention(CLASS)
@Target(FIELD)
public @interface BindView {
    /** 該欄位要綁定的 View ID */
    @IdRes int value();
}

注意 @Retention(CLASS)——它保留到 class 檔但不載入虛擬機。凡標為 CLASS 的註解,通常都會配套一個 AbstractProcessor 實作,在編譯階段完成處理。看幾個關鍵方法:

@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(BindArray.class);
    annotations.add(BindBitmap.class);
    annotations.add(BindBool.class);
    annotations.add(BindColor.class);
    annotations.add(BindDimen.class);
    annotations.add(BindDrawable.class);
    annotations.add(BindFloat.class);
    annotations.add(BindInt.class);
    annotations.add(BindString.class);
    annotations.add(BindView.class);
    annotations.add(BindViews.class);
    annotations.addAll(LISTENERS);
    return annotations;
}

這段在宣告:處理器要接管哪些註解。

@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);
        try {
            javaFile.writeTo(filer);
        } catch (IOException e) {
            error(typeElement, "Unable to write binding for type %s: %s",
                    typeElement, e.getMessage());
        }
    }
    return true;
}

這裡就是編譯期的具體處理流程:先找出並解析所有標註目標,再依解析結果產生 Java 原始碼。等到 App 真正在裝置上執行時,findViewById 與 setOnClickListener 的呼叫已經被寫死進那些自動產生的類別裡,完全不必再做查找與解析,也就沒有執行期反射的負擔。這正是編譯期註解在效能上的根本優勢。

EventBus:執行期註解的代表

EventBus 走的是另一條路:執行時才去找出所有被標註的方法,再逐一解析。好處是寫法直觀、侵入性低;代價是每一次事件分發都伴隨反射查找的開銷。因此實務上的結論是——執行期註解通常只適合標記「作用範圍」,把真正的效能關鍵路徑留給編譯期方案或明確的介面實作。

怎麼選

判斷標準很簡單:這段處理是每次執行都要做一次,還是只需要在編譯時算一次?只要結果在編譯期就能確定(視圖綁定、事件綁定、依賴注入的圖形結構),就應該用編譯期註解把它前移。只有在資訊必須等到執行期才知道時(例如事件訂閱關係、執行期才決定的策略),執行期註解才是合理選擇。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved