Android-Apt 注解處理器(二)

本篇是apt文章的第二篇行贪,不太了解注解的童鞋可以先去第一篇學(xué)習(xí)一下注解漾稀,然后再看第二篇。
Android-Apt 注解處理器(一)
在學(xué)完注解以后 我們的注解處理器就能很快的上手了建瘫。

一崭捍、創(chuàng)建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.編寫(xiě)我們自己的注解

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

接口(根據(jù)實(shí)際情況設(shè)計(jì))

public interface IBubble {
    String getBubble();
}

二啰脚、創(chuàng)建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類(lèi)
    implementation 'com.squareup:javapoet:1.10.0'
    // 依賴(lài)我們的注解module
    implementation project(':lib-annotation')
}

sourceCompatibility = "1.8"
targetCompatibility = "1.8  "

2.AbstractProcessor 介紹

  1. void init(ProcessingEnvironment processingEnvironment) 殷蛇;
    初始化、提供一些工具類(lèi) 。
    2.Set<String> getSupportedAnnotationTypes()粒梦;
    支持的注解類(lèi)型收擦,返回一個(gè)Set<String>,將我們要處理的注解全路徑添加進(jìn)去。
    3.SourceVersion getSupportedSourceVersion()谍倦;
    支持的編譯版本 可以指定位 SourceVersion.RELEASE_8、SourceVersion.RELEASE_7等等泪勒。
    4.Set<String> getSupportedOptions()昼蛀;
    獲取支持的選項(xiàng)、可以返回一下參數(shù)圆存。
    5.boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment);
    這是我們要重點(diǎn)注意的方法叼旋,所有的注解處理以及我們要生成文件都會(huì)在這個(gè)方法中進(jìn)行。

3.創(chuàng)建一個(gè)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夫植、實(shí)現(xiàn)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.實(shí)現(xiàn)SourceVersion getSupportedSourceVersion()

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

6.實(shí)現(xiàn)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中獲取到我們傳的參數(shù)

        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) {
            // 不是類(lèi) 跳過(guò)
            if (!(element instanceof TypeElement)) {
                continue;
            }
            TypeElement typeElement = (TypeElement) element;
            // 尋找到帶有Bubble 注解的類(lèi) 
            Bubble bubble = typeElement.getAnnotation(Bubble.class);
            mMessager.printMessage(Diagnostic.Kind.WARNING, bubble + "      " + (bubble == null));
            if (bubble == null) {
                continue;
            }
            mMessager.printMessage(Diagnostic.Kind.WARNING, "找到的類(lèi)**********   " + (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找到的所有類(lèi)**********:   " + 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));
            // 創(chuàng)建一個(gè)IBubble 的List集合
            FieldSpec fieldSpec = FieldSpec.builder(typeName, "mList", Modifier.PRIVATE)
                    .initializer("new $T()", arrayList)
                    .build();
            // 創(chuàng)建個(gè)Field
            FieldSpec str = FieldSpec.builder(String.class, "str", Modifier.PRIVATE)
                    .build();

            // 把我們獲取到的類(lèi) 在我們要生成的java 類(lèi)中new出來(lái)
            CodeBlock.Builder codeblock = CodeBlock.builder();
            for (TypeElement bubble : bubbles) {
                codeblock.addStatement("$N.add(new $T())", fieldSpec.name, ClassName.get(bubble));
            }
            // 創(chuàng)建方法
            MethodSpec init = MethodSpec.constructorBuilder()
                    .addModifiers(Modifier.PUBLIC)
                    .addStatement("str=$S", "555555")
                    .addCode(codeblock.build())
                    .build();
            // 創(chuàng)建一個(gè)方法 獲取到我們的集合
            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();

            // 創(chuàng)建一個(gè)類(lèi) 叫 BubbleClass
            TypeSpec typeSpec = TypeSpec
                    .classBuilder("BubbleClass")
                    .addModifiers(Modifier.PUBLIC)
                    .addMethod(setList)
                    .addMethod(getList)
                    .addMethod(init)
                    .addField(fieldSpec)
                    .addField(str)
                    .build();

            // 創(chuàng)建java文件 并寫(xiě)入
            JavaFile file = JavaFile.builder("com.bubble.apt", typeSpec).build();
            try {
                file.writeTo(mFiler);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return true;
    }

三油讯、使用详民,創(chuàng)建app module

在build.gradle 中添加我們的注解處理器還有注解的依賴(lài)

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

編寫(xiě)一個(gè)類(lèi) 實(shí)現(xiàn)IBubble 并使用我們的注解

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

編譯過(guò)后生成


image.png

到此 我們的注解處理器編寫(xiě)完成,特別注意的就是在使用我們的注解處理器的時(shí)候

要使用

   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) {
            // 不是類(lèi) 跳過(guò)
            if (!(element instanceof TypeElement)) {
                continue;
            }
            TypeElement typeElement = (TypeElement) element;
            // 尋找到帶有Bubble 注解的類(lèi)
            Bubble bubble = typeElement.getAnnotation(Bubble.class);
            mMessager.printMessage(Diagnostic.Kind.WARNING, bubble + "      " + (bubble == null));
            if (bubble == null) {
                continue;
            }
            mMessager.printMessage(Diagnostic.Kind.WARNING, "找到的類(lèi)**********   " + (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找到的所有類(lèi)**********:   " + 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));
            // 創(chuàng)建一個(gè)IBubble 的List集合
            FieldSpec fieldSpec = FieldSpec.builder(typeName, "mList", Modifier.PRIVATE)
                    .initializer("new $T()", arrayList)
                    .build();
            // 創(chuàng)建個(gè)Field
            FieldSpec str = FieldSpec.builder(String.class, "str", Modifier.PRIVATE)
                    .build();

            // 把我們獲取到的類(lèi) 在我們要生成的java 類(lèi)中new出來(lái)
            CodeBlock.Builder codeblock = CodeBlock.builder();
            for (TypeElement bubble : bubbles) {
                codeblock.addStatement("$N.add(new $T())", fieldSpec.name, ClassName.get(bubble));
            }
            // 創(chuàng)建方法
            MethodSpec init = MethodSpec.constructorBuilder()
                    .addModifiers(Modifier.PUBLIC)
                    .addStatement("str=$S", "555555")
                    .addCode(codeblock.build())
                    .build();
            // 創(chuàng)建一個(gè)方法 獲取到我們的集合
            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();

            // 創(chuàng)建一個(gè)類(lèi) 叫 BubbleClass
            TypeSpec typeSpec = TypeSpec
                    .classBuilder("BubbleClass")
                    .addModifiers(Modifier.PUBLIC)
                    .addMethod(setList)
                    .addMethod(getList)
                    .addMethod(init)
                    .addField(fieldSpec)
                    .addField(str)
                    .build();

            // 創(chuàng)建java文件 并寫(xiě)入
            JavaFile file = JavaFile.builder("com.bubble.apt", typeSpec).build();
            try {
                file.writeTo(mFiler);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return true;
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末陌兑,一起剝皮案震驚了整個(gè)濱河市沈跨,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌兔综,老刑警劉巖饿凛,帶你破解...
    沈念sama閱讀 219,366評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異软驰,居然都是意外死亡涧窒,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,521評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門(mén)锭亏,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)纠吴,“玉大人,你說(shuō)我怎么就攤上這事慧瘤∥叵螅” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 165,689評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵碑隆,是天一觀的道長(zhǎng)恭陡。 經(jīng)常有香客問(wèn)我,道長(zhǎng)上煤,這世上最難降的妖魔是什么休玩? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,925評(píng)論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上拴疤,老公的妹妹穿的比我還像新娘永部。我一直安慰自己,他們只是感情好呐矾,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,942評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布苔埋。 她就那樣靜靜地躺著,像睡著了一般蜒犯。 火紅的嫁衣襯著肌膚如雪组橄。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 51,727評(píng)論 1 305
  • 那天罚随,我揣著相機(jī)與錄音玉工,去河邊找鬼。 笑死淘菩,一個(gè)胖子當(dāng)著我的面吹牛遵班,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播潮改,決...
    沈念sama閱讀 40,447評(píng)論 3 420
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼狭郑,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了汇在?” 一聲冷哼從身側(cè)響起愿阐,我...
    開(kāi)封第一講書(shū)人閱讀 39,349評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎趾疚,沒(méi)想到半個(gè)月后缨历,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,820評(píng)論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡糙麦,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,990評(píng)論 3 337
  • 正文 我和宋清朗相戀三年辛孵,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片赡磅。...
    茶點(diǎn)故事閱讀 40,127評(píng)論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡魄缚,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出焚廊,到底是詐尸還是另有隱情冶匹,我是刑警寧澤,帶...
    沈念sama閱讀 35,812評(píng)論 5 346
  • 正文 年R本政府宣布咆瘟,位于F島的核電站嚼隘,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏袒餐。R本人自食惡果不足惜飞蛹,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,471評(píng)論 3 331
  • 文/蒙蒙 一谤狡、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧卧檐,春花似錦墓懂、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 32,017評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至盈罐,卻和暖如春榜跌,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背暖呕。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,142評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留苞氮,地道東北人湾揽。 一個(gè)月前我還...
    沈念sama閱讀 48,388評(píng)論 3 373
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像笼吟,于是被迫代替她去往敵國(guó)和親库物。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,066評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容