Android-Apt 注解处理器(二)

本篇是apt文章的第二篇,不太了解注解的童鞋可以先去第一篇学习一下注解,然后再看第二篇。
Android-Apt 注解处理器(一)
在学完注解以后 我们的注解处理器就能很快的上手了。

一、创建annotation 注解module ,注意:该module是java modle不是Android module

1.build.gradle配置

apply plugin: 'java-library'

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
}

sourceCompatibility = "1.7"
targetCompatibility = "1.7"

2.编写我们自己的注解

@Retention(RetentionPolicy.CLASS)
@Documented
@Target({ElementType.TYPE, ElementType.FIELD})
public @interface Bubble {
    String name() default "123";
}

接口(根据实际情况设计)

public interface IBubble {
    String getBubble();
}

二、创建annotationProcessor module 该module也是java module

1.build.gradle配置

apply plugin: 'java-library'

dependencies {
    annotationProcessor 'com.google.auto.service:auto-service:1.0-rc4'
    implementation 'com.google.auto.service:auto-service:1.0-rc4'
    // 用于生成java类
    implementation 'com.squareup:javapoet:1.10.0'
    // 依赖我们的注解module
    implementation project(':lib-annotation')
}

sourceCompatibility = "1.8"
targetCompatibility = "1.8  "

2.AbstractProcessor 介绍

  1. void init(ProcessingEnvironment processingEnvironment) ;
    初始化、提供一些工具类 。
    2.Set<String> getSupportedAnnotationTypes();
    支持的注解类型,返回一个Set<String>,将我们要处理的注解全路径添加进去。
    3.SourceVersion getSupportedSourceVersion();
    支持的编译版本 可以指定位 SourceVersion.RELEASE_8、SourceVersion.RELEASE_7等等。
    4.Set<String> getSupportedOptions();
    获取支持的选项、可以返回一下参数。
    5.boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment);
    这是我们要重点注意的方法,所有的注解处理以及我们要生成文件都会在这个方法中进行。

3.创建一个BubbleProcessor 继承AbstractProcessor,在init里面获取到processingEnvironment提供的各种工具

@AutoService(Processor.class)
@SupportedAnnotationTypes("com.gzgxinfo.lib_annotation.Bubble")
@SupportedSourceVersion(SourceVersion.RELEASE_8)
public class BubbleProcessor extends AbstractProcessor {
    private Filer mFiler;
    private Messager mMessager;
    private Elements mElements;

    @Override
    public synchronized void init(ProcessingEnvironment processingEnvironment) {
        super.init(processingEnvironment);
        mFiler = processingEnvironment.getFiler();
        mMessager = processingEnvironment.getMessager();
        mElements = processingEnvironment.getElementUtils();
        mMessager.printMessage(Diagnostic.Kind.WARNING, "初始化");
    }
    @Override
    public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) {
        mMessager.printMessage(Diagnostic.Kind.WARNING, "================================================");
        return true;
    }
}

4、实现getSupportedAnnotationTypes 方法返回我们要处理的注解

    @Override
    public Set<String> getSupportedAnnotationTypes() {
        Set<String> set = new LinkedHashSet<>();
        set.add(Bubble.class.getCanonicalName());
        mMessager.printMessage(Diagnostic.Kind.WARNING, Bubble.class.getName());
        return set;
    }

5.实现SourceVersion getSupportedSourceVersion()

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

6.实现Set<String> getSupportedOptions()


    @Override
    public Set<String> getSupportedOptions() {
        Set<String> set = new LinkedHashSet<>();
        set.add("BUBBLE");
        return set;
    }

在使用注解处理器的module的build.gradle中

defaultConfig {
        applicationId "com.test.demo2"
        minSdkVersion 16
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        javaCompileOptions {
            annotationProcessorOptions {
                arguments = [BUBBLE: "我是option"]
            }
        }
    }

在init中获取到我们传的参数

        Map<String, String> options = processingEnvironment.getOptions();
        mMessager.printMessage(Diagnostic.Kind.WARNING, "BUBBLE:"+options.get("BUBBLE"));

输出:
image.png

6.下面是最重要的方法,process

 @Override
    public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) {
        mMessager.printMessage(Diagnostic.Kind.WARNING, "================================================");


        List<TypeElement> bubbles = new ArrayList<>();
        Set<? extends Element> rootElements = roundEnvironment.getRootElements();
        for (Element element : rootElements) {
            // 不是类 跳过
            if (!(element instanceof TypeElement)) {
                continue;
            }
            TypeElement typeElement = (TypeElement) element;
            // 寻找到带有Bubble 注解的类 
            Bubble bubble = typeElement.getAnnotation(Bubble.class);
            mMessager.printMessage(Diagnostic.Kind.WARNING, bubble + "      " + (bubble == null));
            if (bubble == null) {
                continue;
            }
            mMessager.printMessage(Diagnostic.Kind.WARNING, "找到的类**********   " + (typeElement.getInterfaces().contains(IBubble.class)));
            mMessager.printMessage(Diagnostic.Kind.WARNING, typeElement.getQualifiedName());
            // 添加到集合
            bubbles.add(typeElement);
        }

        for (TypeElement bubble : bubbles) {
            mMessager.printMessage(Diagnostic.Kind.WARNING, "\n\n\n找到的所有类**********:   " + bubble);
        }
        if (!bubbles.isEmpty()) {

            ClassName list = ClassName.get("java.util", "List");
            ClassName arrayList = ClassName.get("java.util", "ArrayList");
            ParameterizedTypeName typeName = ParameterizedTypeName.get(list, ClassName.get(IBubble.class));
            // 创建一个IBubble 的List集合
            FieldSpec fieldSpec = FieldSpec.builder(typeName, "mList", Modifier.PRIVATE)
                    .initializer("new $T()", arrayList)
                    .build();
            // 创建个Field
            FieldSpec str = FieldSpec.builder(String.class, "str", Modifier.PRIVATE)
                    .build();

            // 把我们获取到的类 在我们要生成的java 类中new出来
            CodeBlock.Builder codeblock = CodeBlock.builder();
            for (TypeElement bubble : bubbles) {
                codeblock.addStatement("$N.add(new $T())", fieldSpec.name, ClassName.get(bubble));
            }
            // 创建方法
            MethodSpec init = MethodSpec.constructorBuilder()
                    .addModifiers(Modifier.PUBLIC)
                    .addStatement("str=$S", "555555")
                    .addCode(codeblock.build())
                    .build();
            // 创建一个方法 获取到我们的集合
            MethodSpec getList = MethodSpec.methodBuilder("getList")
                    .addModifiers(Modifier.PUBLIC)
                    .returns(typeName)
                    .addStatement("return $N", fieldSpec.name)
                    .build();
            MethodSpec setList = MethodSpec.methodBuilder("setList")
                    .addParameter(ClassName.get(IBubble.class), "item")
                    .addModifiers(Modifier.PUBLIC)
                    .addStatement("$N.add(item)", fieldSpec.name)
                    .build();

            // 创建一个类 叫 BubbleClass
            TypeSpec typeSpec = TypeSpec
                    .classBuilder("BubbleClass")
                    .addModifiers(Modifier.PUBLIC)
                    .addMethod(setList)
                    .addMethod(getList)
                    .addMethod(init)
                    .addField(fieldSpec)
                    .addField(str)
                    .build();

            // 创建java文件 并写入
            JavaFile file = JavaFile.builder("com.bubble.apt", typeSpec).build();
            try {
                file.writeTo(mFiler);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return true;
    }

三、使用,创建app module

在build.gradle 中添加我们的注解处理器还有注解的依赖

    implementation project(':lib-annotation')
    annotationProcessor project(":lib-apt")

编写一个类 实现IBubble 并使用我们的注解

@Bubble
public class Bubble1 implements IBubble {
    @Override
    public String getBubble() {
        return "Bubble1";
    }
}

编译过后生成


image.png

到此 我们的注解处理器编写完成,特别注意的就是在使用我们的注解处理器的时候

要使用

   annotationProcessor project(":lib-apt")

而不是

   implementation project(":lib-apt")

下面贴出完整代码

package com.bubble.lib_apt;

import com.bubble.lib_annotation.Bubble;
import com.bubble.lib_annotation.IBubble;
import com.google.auto.service.AutoService;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.CodeBlock;
import com.squareup.javapoet.FieldSpec;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.ParameterizedTypeName;
import com.squareup.javapoet.TypeSpec;

import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.Filer;
import javax.annotation.processing.Messager;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.Processor;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.annotation.processing.SupportedSourceVersion;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.util.Elements;
import javax.tools.Diagnostic;

@AutoService(Processor.class)
@SupportedAnnotationTypes("com.bubbble.lib_annotation.Bubble")
@SupportedSourceVersion(SourceVersion.RELEASE_8)
public class BubbleProcessor extends AbstractProcessor {
    private Filer mFiler;
    private Messager mMessager;
    private Elements mElements;

    @Override
    public synchronized void init(ProcessingEnvironment processingEnvironment) {
        super.init(processingEnvironment);
        mFiler = processingEnvironment.getFiler();
        mMessager = processingEnvironment.getMessager();
        mElements = processingEnvironment.getElementUtils();
        mMessager.printMessage(Diagnostic.Kind.WARNING, "初始化");

        Map<String, String> options = processingEnvironment.getOptions();
        mMessager.printMessage(Diagnostic.Kind.WARNING, "BUBBLE:" + options.get("BUBBLE"));
    }

    @Override
    public Set<String> getSupportedAnnotationTypes() {
        Set<String> set = new LinkedHashSet<>();
        set.add(Bubble.class.getCanonicalName());
        mMessager.printMessage(Diagnostic.Kind.WARNING, Bubble.class.getCanonicalName());
        return set;
    }

    @Override
    public Set<String> getSupportedOptions() {
        Set<String> set = new LinkedHashSet<>();
        set.add("BUBBLE");
        return set;
    }

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

    @Override
    public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) {
        mMessager.printMessage(Diagnostic.Kind.WARNING, "================================================");


        List<TypeElement> bubbles = new ArrayList<>();
        Set<? extends Element> rootElements = roundEnvironment.getRootElements();
        for (Element element : rootElements) {
            // 不是类 跳过
            if (!(element instanceof TypeElement)) {
                continue;
            }
            TypeElement typeElement = (TypeElement) element;
            // 寻找到带有Bubble 注解的类
            Bubble bubble = typeElement.getAnnotation(Bubble.class);
            mMessager.printMessage(Diagnostic.Kind.WARNING, bubble + "      " + (bubble == null));
            if (bubble == null) {
                continue;
            }
            mMessager.printMessage(Diagnostic.Kind.WARNING, "找到的类**********   " + (typeElement.getInterfaces().contains(IBubble.class)));
            mMessager.printMessage(Diagnostic.Kind.WARNING, typeElement.getQualifiedName());
            // 添加到集合
            bubbles.add(typeElement);
        }

        for (TypeElement bubble : bubbles) {
            mMessager.printMessage(Diagnostic.Kind.WARNING, "\n\n\n找到的所有类**********:   " + bubble);
        }
        if (!bubbles.isEmpty()) {

            ClassName list = ClassName.get("java.util", "List");
            ClassName arrayList = ClassName.get("java.util", "ArrayList");
            ParameterizedTypeName typeName = ParameterizedTypeName.get(list, ClassName.get(IBubble.class));
            // 创建一个IBubble 的List集合
            FieldSpec fieldSpec = FieldSpec.builder(typeName, "mList", Modifier.PRIVATE)
                    .initializer("new $T()", arrayList)
                    .build();
            // 创建个Field
            FieldSpec str = FieldSpec.builder(String.class, "str", Modifier.PRIVATE)
                    .build();

            // 把我们获取到的类 在我们要生成的java 类中new出来
            CodeBlock.Builder codeblock = CodeBlock.builder();
            for (TypeElement bubble : bubbles) {
                codeblock.addStatement("$N.add(new $T())", fieldSpec.name, ClassName.get(bubble));
            }
            // 创建方法
            MethodSpec init = MethodSpec.constructorBuilder()
                    .addModifiers(Modifier.PUBLIC)
                    .addStatement("str=$S", "555555")
                    .addCode(codeblock.build())
                    .build();
            // 创建一个方法 获取到我们的集合
            MethodSpec getList = MethodSpec.methodBuilder("getList")
                    .addModifiers(Modifier.PUBLIC)
                    .returns(typeName)
                    .addStatement("return $N", fieldSpec.name)
                    .build();
            MethodSpec setList = MethodSpec.methodBuilder("setList")
                    .addParameter(ClassName.get(IBubble.class), "item")
                    .addModifiers(Modifier.PUBLIC)
                    .addStatement("$N.add(item)", fieldSpec.name)
                    .build();

            // 创建一个类 叫 BubbleClass
            TypeSpec typeSpec = TypeSpec
                    .classBuilder("BubbleClass")
                    .addModifiers(Modifier.PUBLIC)
                    .addMethod(setList)
                    .addMethod(getList)
                    .addMethod(init)
                    .addField(fieldSpec)
                    .addField(str)
                    .build();

            // 创建java文件 并写入
            JavaFile file = JavaFile.builder("com.bubble.apt", typeSpec).build();
            try {
                file.writeTo(mFiler);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return true;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容