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

動手做一個 ButterKnife:注解與編譯期處理的入門實踐

編輯:關於 Android 程式設計

ButterKnife 幾乎人人用過,最直接的收益就是省下一堆 findViewById。既然原理不複雜,那我們就自己刻一個,取名 BBKnife。

先看 ButterKnife 做了什麼

使用時我們這樣寫:

class ExampleActivity extends Activity {

    @BindView(R.id.title)    TextView title;
    @BindView(R.id.subtitle) TextView subtitle;
    @BindView(R.id.footer)   TextView footer;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.simple_activity);
        ButterKnife.bind(this);
        // TODO Use fields...
    }
}

編譯之後,它會生成一個與 Activity 同名的輔助類 ExampleActivity$ViewBinder,內容就是那串 findViewById:

public void bind(ExampleActivity activity) {
    activity.subtitle = (android.widget.TextView) activity.findViewById(2130968578);
    activity.footer   = (android.widget.TextView) activity.findViewById(2130968579);
    activity.title    = (android.widget.TextView) activity.findViewById(2130968577);
}

所以 BBKnife 要做的事就很明確了:在編譯期掃描注解,生成這樣一個輔助類。

四個步驟

  1. 定義注解
  2. 在編譯期處理注解
  3. 生成輔助類
  4. 在執行期呼叫輔助類

步驟一:建立工程

新建一個專案,然後新增一個 module,類型選 Java Library。

步驟二:定義注解

這個注解作用於屬性上,帶一個整型參數,用法等同 @BindView(R.id.title):

/**
 * Created by hanks on 2016/7/31.
 */
@Documented
@Retention(RetentionPolicy.CLASS)
@Target(ElementType.FIELD)
public @interface BindView {
    int value();
}

這裡 Retention 選 CLASS 而不是 RUNTIME,因為我們只需要在編譯期看到它,執行期並不需要反射讀取,這樣也比較省效能。

步驟三:編譯期處理注解並生成輔助類

/**
 * 編譯期間處理注解
 * Created by hanks on 2016/7/31.
 */
@SupportedAnnotationTypes("xyz.hanks.BindView")
@SupportedSourceVersion(SourceVersion.RELEASE_7)
public class BindViewProcessor extends AbstractProcessor {

    private Messager messager;

    public static final String SUFFIX = "$ViewBinder";

    @Override
    public synchronized void init(ProcessingEnvironment processingEnv) {
        super.init(processingEnv);
        messager = processingEnv.getMessager();
    }

    @Override
    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
        // key 是類名,value 是該類中帶注解的屬性
        Map<String, List<VariableElement>> map = new HashMap<>();

        // 遍歷所有被 BindView 標註的元素
        for (Element element : roundEnv.getElementsAnnotatedWith(BindView.class)) {
            if (element == null || !(element instanceof VariableElement)) {
                continue;
            }
            VariableElement variableElement = (VariableElement) element;

            // 取得屬性所在的類名
            String className = element.getEnclosingElement().getSimpleName().toString();

            List<VariableElement> variableElementList = map.get(className);
            if (variableElementList == null) {
                variableElementList = new ArrayList<>();
                map.put(className, variableElementList);
            }
            variableElementList.add(variableElement);
        }

        generate(map);
        return true;
    }

    private void generate(Map<String, List<VariableElement>> map) {
        if (map == null || map.size() == 0) {
            return;
        }

        for (String className : map.keySet()) {
            List<VariableElement> variableElementList = map.get(className);
            if (variableElementList == null || variableElementList.size() <= 0) {
                continue;
            }

            // 取得完整包名
            String packageName = variableElementList.get(0)
                    .getEnclosingElement().getEnclosingElement().toString();

            StringBuilder builder = new StringBuilder()
                    .append("package ").append(packageName).append(";\n\n")
                    .append("public class ").append(className).append(SUFFIX).append(" {\n")
                    .append("    public void bind(Object target) {\n")
                    .append("        ").append(className).append(" activity = (")
                    .append(className).append(") target;\n");

            for (VariableElement variableElement : variableElementList) {
                BindView bindView = variableElement.getAnnotation(BindView.class);
                log(bindView.toString());
                builder.append("        activity.")
                        .append(variableElement.getSimpleName().toString())
                        .append(" = (").append(variableElement.asType()).append(") ")
                        .append("activity.findViewById(").append(bindView.value()).append(");\n");
            }

            builder.append("    }\n}\n");

            // 輸出檔案
            try {
                String bindViewClassName = packageName + "." + className + SUFFIX;
                JavaFileObject source = processingEnv.getFiler().createSourceFile(bindViewClassName);
                Writer writer = source.openWriter();
                writer.write(builder.toString());
                writer.flush();
                writer.close();
            } catch (IOException e) {
                log(e.getMessage());
            }
        }
    }

    private void log(String msg) {
        messager.printMessage(Diagnostic.Kind.WARNING, msg);
    }
}

幾個實作上的注意事項:

  • 一定要加上 @SupportedAnnotationTypes 與 @SupportedSourceVersion,因為 AbstractProcessor 內部有相關校驗。
  • 編譯期的訊息輸出要用 processingEnv.getMessager().printMessage(),不能用 System.out 或 Log.i——那時候還沒跑到執行期。
  • 取類名與包名時要分清是「完整路徑」還是「簡單名稱」,取錯就會生成出無法編譯的檔案。

接著在 src/main/resources/META-INF/services 下建立名為 javax.annotation.processing.Processor 的檔案,內容寫上你的處理器完整類名。javac 會自動讀取這個檔案並完成註冊。

步驟四:執行期呼叫輔助類

呼叫 BBKnife.bind(activity) 時,用反射找到「類名 + $ViewBinder」的輔助類並執行它的 bind 方法:

public class BBKnife {

    public static void bind(Object view) {
        try {
            String cla = view.getClass().getName() + BindViewProcessor.SUFFIX;
            Class clazz = Class.forName(cla);
            Object instance = clazz.newInstance();
            Method bind = clazz.getMethod("bind", Object.class);
            bind.invoke(instance, view);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

導出 jar

build 之後,build/libs 目錄下就會有對應的 jar 檔。

使用方式

把 jar 複製到 app 模組的 libs 目錄,並在 build.gradle 中引入 android-apt 外掛:

apply plugin: 'com.android.application'
apply plugin: 'com.neenbedankt.android-apt'   // 使用 apt

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
    }
}

android {
    compileSdkVersion 24
    buildToolsVersion "24.0.1"

    defaultConfig {
        applicationId "xyz.hanks.bbknifeproject"
        minSdkVersion 15
        targetSdkVersion 24
        versionCode 1
        versionName "1.0"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_7
        targetCompatibility JavaVersion.VERSION_1_7
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:24.1.1'
}

在 MainActivity 中使用,寫法和 ButterKnife 幾乎一致:

public class MainActivity extends AppCompatActivity {

    @BindView(R.id.bb_button) Button   mButton;
    @BindView(R.id.bb_image)  ImageView mImage;
    @BindView(R.id.bb_text)   TextView  mText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        BBKnife.bind(this);

        mButton.setText("hanks.xyz");
        mText.setText("hanks.xyz");
        mImage.setImageResource(R.mipmap.ic_launcher);
    }
}

編譯後可以觀察到生成的輔助類 MainActivity$ViewBinder.java:

public class MainActivity$ViewBinder {

    public void bind(Object target) {
        MainActivity activity = (MainActivity) target;
        activity.mButton = (android.widget.Button)   activity.findViewById(2131427412);
        activity.mImage  = (android.widget.ImageView) activity.findViewById(2131427414);
        activity.mText   = (android.widget.TextView)  activity.findViewById(2131427413);
    }
}

回顧一下學到了什麼

這篇真正練習到的不是「怎麼省 findViewById」,而是三個更有價值的能力:

  • 注解的 Retention 與 Target 怎麼選,取決於你希望它在編譯期可見還是執行期可見。
  • AbstractProcessor 的用法:process 拿到標註元素、Filer 輸出檔案、Messager 輸出診斷訊息。
  • META-INF/services 的 SPI 註冊機制,這是 javac 找到你的處理器的唯一途徑。

把同一套骨架換成 @OnClick、@BindString 甚至自訂的日誌切面,都不難。真正要留意的是執行期的反射開銷——這也是 ButterKnife 選擇編譯期生成程式碼、而不是執行期反射的原因。

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