【Android】APT

介紹

APT(Annotation Processing Tool)即注解處理器,是一種處理注解的工具,確切的說它是javac的一個工具,它用來在編譯時掃描和處理注解。注解處理器以Java代碼(或者編譯過的字節(jié)碼)作為輸入,生成.java文件作為輸出。
簡單來說就是在編譯期,通過注解生成.java文件。

作用

使用APT的優(yōu)點(diǎn)就是方便、簡單,可以少些很多重復(fù)的代碼。

用過ButterKnife、Dagger、EventBus等注解框架的同學(xué)就能感受到,利用這些框架可以少些很多代碼,只要寫一些注解就可以了。
其實(shí),他們不過是通過注解,生成了一些代碼。通過對APT的學(xué)習(xí),你就會發(fā)現(xiàn),他們很強(qiáng)~~~

實(shí)現(xiàn)

說了這么多,動手試試

目標(biāo)
通過APT實(shí)現(xiàn)一個功能,通過對View變量的注解,實(shí)現(xiàn)View的綁定(類似于ButterKnife中的@BindView

(參考自這里

創(chuàng)建項目
創(chuàng)建Android Module命名為app
創(chuàng)建Java library Module命名為 apt-annotation
創(chuàng)建Java library Module命名為 apt-processor 依賴 apt-annotation
創(chuàng)建Android library Module 命名為apt-library依賴 apt-annotation、auto-service

結(jié)構(gòu)如下


功能主要分為三個部分

  • apt-annotation:自定義注解,存放@BindView
  • apt-processor:注解處理器,根據(jù)apt-annotation中的注解,在編譯期生成xxxActivity_ViewBinding.java代碼
  • apt-library:工具類,調(diào)用xxxActivity_ViewBinding.java中的方法,實(shí)現(xiàn)View的綁定。

關(guān)系如下


app?app不是功能代碼,只是用來驗(yàn)證功能的~~~

1、apt-annotation(自定義注解)

創(chuàng)建注解類BindView

@Retention(RetentionPolicy.CLASS)
@Target(ElementType.FIELD)
public @interface BindView {
    int value();
}

@Retention(RetentionPolicy.CLASS):表示編譯時注解
@Target(ElementType.FIELD):表示注解范圍為類成員(構(gòu)造方法、方法、成員變量)

@Retention: 定義被保留的時間長短
RetentionPoicy.SOURCE、RetentionPoicy.CLASS、RetentionPoicy.RUNTIME
@Target: 定義所修飾的對象范圍
TYPE、FIELD、METHOD、PARAMETER、CONSTRUCTOR、LOCAL_VARIABLE等
詳細(xì)內(nèi)容

這里定義了運(yùn)行時注解BindView,其中value()用于獲取對應(yīng)Viewid

2、apt-processor(注解處理器)

(重點(diǎn)部分)

Module中添加依賴

dependencies {
    implementation 'com.google.auto.service:auto-service:1.0-rc2' 
    // Gradle 5.0后需要再加下面這行
    // annotationProcessor  'com.google.auto.service:auto-service:1.0-rc2' 
    implementation project(':apt-annotation')
}

Android Studio升級到3.0以后,Gradle也隨之升級到3.0。implementation替代了之前的compile

創(chuàng)建BindViewProcessor

@AutoService(Processor.class)
public class BindViewProcessor extends AbstractProcessor {

    private Messager mMessager;
    private Elements mElementUtils;
    private Map<String, ClassCreatorProxy> mProxyMap = new HashMap<>();

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

    @Override
    public Set<String> getSupportedAnnotationTypes() {
        HashSet<String> supportTypes = new LinkedHashSet<>();
        supportTypes.add(BindView.class.getCanonicalName());
        return supportTypes;
    }

    @Override
    public SourceVersion getSupportedSourceVersion() {
        return SourceVersion.latestSupported();
    }

    @Override
    public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnv) {
        //根據(jù)注解生成Java文件
        return false;
    }
}
  • init:初始化??梢缘玫?code>ProcessingEnviroment,ProcessingEnviroment提供很多有用的工具類Elements, TypesFiler
  • getSupportedAnnotationTypes:指定這個注解處理器是注冊給哪個注解的,這里說明是注解BindView
  • getSupportedSourceVersion:指定使用的Java版本,通常這里返回SourceVersion.latestSupported()
  • process:可以在這里寫掃描、評估和處理注解的代碼,生成Java文件(process中的代碼下面詳細(xì)說明
@AutoService(Processor.class)
public class BindViewProcessor extends AbstractProcessor {

    private Messager mMessager;
    private Elements mElementUtils;
    private Map<String, ClassCreatorProxy> mProxyMap = new HashMap<>();

    @Override
    public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) {
        mMessager.printMessage(Diagnostic.Kind.NOTE, "processing...");
        mProxyMap.clear();
        //得到所有的注解
        Set<? extends Element> elements = roundEnvironment.getElementsAnnotatedWith(BindView.class);
        for (Element element : elements) {
            VariableElement variableElement = (VariableElement) element;
            TypeElement classElement = (TypeElement) variableElement.getEnclosingElement();
            String fullClassName = classElement.getQualifiedName().toString();
            ClassCreatorProxy proxy = mProxyMap.get(fullClassName);
            if (proxy == null) {
                proxy = new ClassCreatorProxy(mElementUtils, classElement);
                mProxyMap.put(fullClassName, proxy);
            }
            BindView bindAnnotation = variableElement.getAnnotation(BindView.class);
            int id = bindAnnotation.value();
            proxy.putElement(id, variableElement);
        }
        //通過遍歷mProxyMap,創(chuàng)建java文件
        for (String key : mProxyMap.keySet()) {
            ClassCreatorProxy proxyInfo = mProxyMap.get(key);
            try {
                mMessager.printMessage(Diagnostic.Kind.NOTE, " --> create " + proxyInfo.getProxyClassFullName());
                JavaFileObject jfo = processingEnv.getFiler().createSourceFile(proxyInfo.getProxyClassFullName(), proxyInfo.getTypeElement());
                Writer writer = jfo.openWriter();
                writer.write(proxyInfo.generateJavaCode());
                writer.flush();
                writer.close();
            } catch (IOException e) {
                mMessager.printMessage(Diagnostic.Kind.NOTE, " --> create " + proxyInfo.getProxyClassFullName() + "error");
            }
        }

        mMessager.printMessage(Diagnostic.Kind.NOTE, "process finish ...");
        return true;
    }
}

通過roundEnvironment.getElementsAnnotatedWith(BindView.class)得到所有注解elements,然后將elements的信息保存到mProxyMap中,最后通過mProxyMap創(chuàng)建對應(yīng)的Java文件,其中mProxyMapClassCreatorProxyMap集合。

ClassCreatorProxy是創(chuàng)建Java代碼的代理類,如下:

public class ClassCreatorProxy {
    private String mBindingClassName;
    private String mPackageName;
    private TypeElement mTypeElement;
    private Map<Integer, VariableElement> mVariableElementMap = new HashMap<>();

    public ClassCreatorProxy(Elements elementUtils, TypeElement classElement) {
        this.mTypeElement = classElement;
        PackageElement packageElement = elementUtils.getPackageOf(mTypeElement);
        String packageName = packageElement.getQualifiedName().toString();
        String className = mTypeElement.getSimpleName().toString();
        this.mPackageName = packageName;
        this.mBindingClassName = className + "_ViewBinding";
    }

    public void putElement(int id, VariableElement element) {
        mVariableElementMap.put(id, element);
    }

    /**
     * 創(chuàng)建Java代碼
     * @return
     */
    public String generateJavaCode() {
        StringBuilder builder = new StringBuilder();
        builder.append("package ").append(mPackageName).append(";\n\n");
        builder.append("import com.example.gavin.apt_library.*;\n");
        builder.append('\n');
        builder.append("public class ").append(mBindingClassName);
        builder.append(" {\n");

        generateMethods(builder);
        builder.append('\n');
        builder.append("}\n");
        return builder.toString();
    }

    /**
     * 加入Method
     * @param builder
     */
    private void generateMethods(StringBuilder builder) {
        builder.append("public void bind(" + mTypeElement.getQualifiedName() + " host ) {\n");
        for (int id : mVariableElementMap.keySet()) {
            VariableElement element = mVariableElementMap.get(id);
            String name = element.getSimpleName().toString();
            String type = element.asType().toString();
            builder.append("host." + name).append(" = ");
            builder.append("(" + type + ")(((android.app.Activity)host).findViewById( " + id + "));\n");
        }
        builder.append("  }\n");
    }

    public String getProxyClassFullName()
    {
        return mPackageName + "." + mBindingClassName;
    }

    public TypeElement getTypeElement()
    {
        return mTypeElement;
    }
}

上面的代碼主要就是從Elements、TypeElement得到想要的一些信息,如package name、Activity名、變量類型、id等,通過StringBuilder一點(diǎn)一點(diǎn)拼出Java代碼,每個對象分別代表一個對應(yīng)的.java文件。

沒想到吧!Java代碼還可以這樣寫~~
提前看下生成的代碼(不大整齊,被我格式化了)

public class MainActivity_ViewBinding {
    public void bind(com.example.gavin.apttest.MainActivity host) {
        host.mButton = (android.widget.Button) (((android.app.Activity) host).findViewById(2131165218));
        host.mTextView = (android.widget.TextView) (((android.app.Activity) host).findViewById(2131165321));
    }
}

缺陷
通過StringBuilder的方式一點(diǎn)一點(diǎn)來拼寫Java代碼,不但繁瑣還容易寫錯~~

更好的方案
通過javapoet可以更加簡單得生成這樣的Java代碼。(后面會說到)

介紹下依賴庫auto-service
在使用注解處理器需要先聲明,步驟:
1、需要在 processors 庫的 main 目錄下新建 resources 資源文件夾;
2、在 resources文件夾下建立 META-INF/services 目錄文件夾;
3、在 META-INF/services 目錄文件夾下創(chuàng)建 javax.annotation.processing.Processor 文件;
4、在 javax.annotation.processing.Processor 文件寫入注解處理器的全稱,包括包路徑;)
這樣聲明下來也太麻煩了?這就是用引入auto-service的原因。
通過auto-service中的@AutoService可以自動生成AutoService注解處理器是Google開發(fā)的,用來生成 META-INF/services/javax.annotation.processing.Processor 文件的

3、apt-library 工具類

完成了Processor的部分,基本快大功告成了。

BindViewProcessor中創(chuàng)建了對應(yīng)的xxxActivity_ViewBinding.java,我們改怎么調(diào)用?當(dāng)然是反射啦!?。?/p>

Modulebuild.gradle中添加依賴

dependencies {
    implementation project(':apt-annotation')
}

創(chuàng)建注解工具類BindViewTools

public class BindViewTools {

    public static void bind(Activity activity) {

        Class clazz = activity.getClass();
        try {
            Class bindViewClass = Class.forName(clazz.getName() + "_ViewBinding");
            Method method = bindViewClass.getMethod("bind", activity.getClass());
            method.invoke(bindViewClass.newInstance(), activity);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}

apt-library的部分就比較簡單了,通過反射找到對應(yīng)的ViewBinding類,然后調(diào)用其中的bind()方法完成View的綁定。

到目前為止,所有相關(guān)的代碼都寫完了,終于可以拿出來溜溜了


4、app

依賴
Modulebuild.gradle中(Gradle>=2.2

dependencies {
    implementation project(':apt-annotation')
    implementation project(':apt-library')
    annotationProcessor project(':apt-processor')
}

Android Gradle 插件 2.2 版本的發(fā)布,Android Gradle 插件提供了名為 annotationProcessor的功能來完全代替 android-apt


(若Gradle<2.2
Projectbuild.gradle中:

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

Modulebuile.gradle中:

apply plugin: 'com.android.application'
apply plugin: 'com.neenbedankt.android-apt'
dependencies {
    apt project(':apt-processor')
}

使用
MainActivity中,在View的前面加上BindView注解,把id傳入即可

public class MainActivity extends AppCompatActivity {

    @BindView(R.id.tv)
    TextView mTextView;
    @BindView(R.id.btn)
    Button mButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        BindViewTools.bind(this);
        mTextView.setText("bind TextView success");
        mButton.setText("bind Button success");
    }
}

運(yùn)行的結(jié)果想必大家都知道了,不夠?yàn)榱俗C明這個BindView的功能完成了,我還是把圖貼出來

結(jié)果

生成的代碼

上面的功能一直在完成一件事情,那就是生成Java代碼,那么生成的代碼在哪?
app/build/generated/source/apt中可以找到生成的Java文件

目錄

對應(yīng)的代碼(之前已經(jīng)貼過了):

public class MainActivity_ViewBinding {
    public void bind(com.example.gavin.apttest.MainActivity host) {
        host.mButton = (android.widget.Button) (((android.app.Activity) host).findViewById(2131165218));
        host.mTextView = (android.widget.TextView) (((android.app.Activity) host).findViewById(2131165321));
    }
}

通過javapoet生成代碼

上面在ClassCreatorProxy中,通過StringBuilder來生成對應(yīng)的Java代碼。這種做法是比較麻煩的,還有一種更優(yōu)雅的方式,那就是javapoet

先添加依賴

dependencies {
    implementation 'com.squareup:javapoet:1.10.0'
}

然后在ClassCreatorProxy

public class ClassCreatorProxy {
    //省略部分代碼...

    /**
     * 創(chuàng)建Java代碼
     * @return
     */
    public TypeSpec generateJavaCode2() {
        TypeSpec bindingClass = TypeSpec.classBuilder(mBindingClassName)
                .addModifiers(Modifier.PUBLIC)
                .addMethod(generateMethods2())
                .build();
        return bindingClass;

    }

    /**
     * 加入Method
     */
    private MethodSpec generateMethods2() {
        ClassName host = ClassName.bestGuess(mTypeElement.getQualifiedName().toString());
        MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("bind")
                .addModifiers(Modifier.PUBLIC)
                .returns(void.class)
                .addParameter(host, "host");

        for (int id : mVariableElementMap.keySet()) {
            VariableElement element = mVariableElementMap.get(id);
            String name = element.getSimpleName().toString();
            String type = element.asType().toString();
            methodBuilder.addCode("host." + name + " = " + "(" + type + ")(((android.app.Activity)host).findViewById( " + id + "));");
        }
        return methodBuilder.build();
    }


    public String getPackageName() {
        return mPackageName;
    }
}

最后在 BindViewProcessor

    @Override
    public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) {
        //省略部分代碼...
        //通過javapoet生成
        for (String key : mProxyMap.keySet()) {
            ClassCreatorProxy proxyInfo = mProxyMap.get(key);
            JavaFile javaFile = JavaFile.builder(proxyInfo.getPackageName(), proxyInfo.generateJavaCode2()).build();
            try {
                // 生成文件
                javaFile.writeTo(processingEnv.getFiler());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        mMessager.printMessage(Diagnostic.Kind.NOTE, "process finish ...");
        return true;
    }

相比用StringBuilderJava代碼,明顯簡潔和很多。最后生成的代碼跟之前是一樣的,就不貼出來了。

javapoet詳細(xì)用法

Tips

1、如果是ElementType.METHOD類型的注解,解析Element時使用ExecutableElement,而不是Symbol.MethodSymbol,否則編譯運(yùn)行的時候沒問題,打包的時候會報錯。別問我時為什么知道的...

2、gradle升級到3.4.0以后,AutoService要這么用

implementation 'com.google.auto.service:auto-service:1.0-rc2'
annotationProcessor  'com.google.auto.service:auto-service:1.0-rc2' 

源碼

GitHub

參考

編譯期注解之APT
詳細(xì)介紹編譯時注解的使用方法
Android 編譯時注解-提升
Android APT及基于APT的簡單應(yīng)用
Android 打造編譯時注解解析框架 這只是一個開始
你必須知道的APT、annotationProcessor、android-apt、Provided、自定義注解

以上有錯誤之處,感謝指出

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容