官方文檔:Getting Started with the Annotation PRocessing Tool (apt)
如果想學習APT,那么就必須先了解Annotation的基礎,這里附加我另外一篇文章的地址: Annotation - QQ_20198405的博客 - 博客頻道 - CSDN.NET
APT(Annotation Processing Tool)是一種處理注解的工具,它對源代碼文件進行檢測找出其中的Annotation,使用Annotation進行額外的處理。 Annotation處理器在處理Annotation時可以根據源文件中的Annotation生成額外的源文件和其它的文件(文件具體內容由Annotation處理器的編寫者決定),APT還會編譯生成的源文件和原來的源文件,將它們一起生成class文件。
新建一個名稱為annotation的java Library,主要放置一些項目中需要使用到的Annotation和關聯代碼。 這里簡單自定義了一個注解:
@Target(ElementType.TYPE)@Retention(RetentionPolicy.CLASS)public @interface AptAnnotation {}新建一個名為compiler的Java Library,這個類將會寫代碼生成的相關代碼。核心就是在這里。
tasks.withType
是設置編碼格式,避免AptProcesser 中的中文注釋報錯依賴上面創建的annotation Module。生成代碼相關的邏輯就放在這里。
@AutoService(Processor.class) public class AptProcesser extends AbstractProcessor { @Override public Set<String> getSupportedAnnotationTypes() { return Collections.singleton(AptAnnotation.class.getCanonicalName()); } @Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { return false; } }我們接下來要生成下面這個HelloWorld的代碼:
package com.example.helloworld; public final class HelloWorld { public static void main(String[] args) { System.out.println("Hello, JavaPoet!"); } }修改上述AptProcesser 的process方法
@Override public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) { 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(); try { javaFile.writeTo(processingEnv.getFiler()); } catch (IOException e) { e.printStackTrace(); } return false; }點擊Android Studio的ReBuild Project,可以在在app的 build/generated/source/apt/debug 目錄下,即可看到生成的代碼。
到目前我們還沒有使用注解,上面的@AptAnnotation 也沒有實際用上,下面我們做一些更加實際的代碼生成。實現基于注解的View,代替項目中的findByView 。這里僅僅是學習怎么用APT,如果真的想用DI框架,推薦使用ButterKnife,功能全面。
實際上就是通過apt生成以下代碼:
public final class DIMainActivity { public static void bindView(MainActivity activity) { activity.textView1 = (android.widget.TextView) activity.findViewById(2131427413); activity.textView2 = (android.widget.TextView) activity.findViewById(2131427414); activity.textView3 = (android.widget.TextView) activity.findViewById(2131427415); }}常用Element子類
TypeElement:類ExecutableElement:成員方法VariableElement:成員變量
通過包名和類名獲取TypeName
TypeName targetClassName = ClassName.get("PackageName", "ClassName");通過Element獲取TypeNameTypeName type = TypeName.get(element.asType());獲取TypeElement的包名String packageName = processingEnv.getElementUtils().getPackageOf(type).getQualifiedName().toString();獲取TypeElement的所有成員變量和成員方法List<? extends Element> members = processingEnv.getElementUtils().getAllMembers(typeElement);總結:
推薦閱讀dagger2、dbflow、ButterKnife等基于apt的開源項目代碼。JavaPoet 也有很多例子可以學習。
源碼傳送 參考: Android APT(編譯時代碼生成)最佳實踐 - 推酷 例子: 代碼傳送(稍加注釋) Android 利用 APT 技術在編譯期生成代碼 - hb707934728的博客 - 博客頻道 - CSDN.NET
相關文章: android-apt 翻譯 - 簡書 原文hvisser / android-apt — Bitbucket Annotation-Processing-Tool詳解 | qiushao http://qiushao.net/2015/07/07/Annotation-Processing-Tool%E8%AF%A6%E8%A7%A3/ AndroidSutdio 編譯時自動生成源代碼 | Septenary http://www.septenary.cn/2015/12/19/AndroidSutdio-%E7%BC%96%E8%AF%91%E6%97%B6%E8%87%AA%E5%8A%A8%E7%94%9F%E6%88%90%E6%BA%90%E4%BB%A3%E7%A0%81/
Android 打造編譯時注解解析框架 這只是一個開始 - Hongyang - 博客頻道 - CSDN.NET http://blog.csdn.net/lmj623565791/article/details/43452969 Android 如何編寫基于編譯時注解的項目 - Hongyang - 博客頻道 - CSDN.NET http://blog.csdn.net/lmj623565791/article/details/51931859
bug解決: Android Studio出現Error:No service of type Factor… - 簡書 http://www.jianshu.com/p/c4f4894ad215 Android Studio Error—Gradle: 錯誤:編碼 GBK 的不可映射字符的 - 黑暗領域 - 博客頻道 - CSDN.NET http://blog.csdn.net/sljjyy/article/details/11976099
新聞熱點
疑難解答