安卓开发-处理自定义注解

一、创建一个Module用于存放自定义注解
1 创建Module MyAnnotation



2 添加build.gradle配置

apply plugin: 'java-library'

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

sourceCompatibility = "1.7"
targetCompatibility = "1.7"

二、创建一个Module用于存放注解处理类Processor
1 创建Module MyProcessor
2 添加build.gradle配置

apply plugin: 'java-library'

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation project(':MyAnnotation')
    implementation 'com.google.auto.service:auto-service:1.0-rc2' //build的时候会执行注解处理类
    implementation 'com.squareup:javapoet:1.7.0'//辅助生成java文件
}

sourceCompatibility = "1.7"
targetCompatibility = "1.7"

三、app包的build.gradle
添加

implementation project(':MyAnnotation')
annotationProcessor project(':MyProcessor')

四、自定义注解TestAnnotation.java

@Retention(RetentionPolicy.RUNTIME)
public @interface TestAnnotation {
    String name() default "123";
}

五、编写注解处理类

@AutoService(Processor.class)//自动生成 javax.annotation.processing.IProcessor 文件,使得自定义注解处理类可以在编译时执行
@SupportedSourceVersion(SourceVersion.RELEASE_8)//java版本支持
@SupportedAnnotationTypes({"com.example.myannotation.TestAnnotation"})//标注注解处理器支持的注解类型,就是我们刚才定义的接口Test,可以写入多个注解类型。
public class MyProcessor extends AbstractProcessor{

    private Messager messager;
    private Elements elements;
    private Filer filer;

    @Override
    public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) {
        filer = processingEnv.getFiler();
        elements = processingEnv.getElementUtils();
        messager = processingEnv.getMessager();


        MethodSpec.Builder builder = MethodSpec.methodBuilder("Log")//生成方法
                .addModifiers(Modifier.PUBLIC,Modifier.STATIC)
                .addJavadoc("@方法")
                .returns(void.class);

        for(TypeElement e: ElementFilter.typesIn(roundEnvironment.getElementsAnnotatedWith(TestAnnotation.class))){
            messager.printMessage(Diagnostic.Kind.NOTE,"print: "+e.toString());

            TestAnnotation annotation = e.getAnnotation(TestAnnotation.class);
            String name = annotation.name();
            builder.addStatement("$T.out.println($S)", System.class,name);//添加方法体
            messager.printMessage(Diagnostic.Kind.NOTE,"print: add name-->"+name);
        }

        TypeSpec typeSpec = TypeSpec.classBuilder("LogUtils")//生成类
                .addModifiers(Modifier.PUBLIC,Modifier.FINAL)//类的属性
                .addMethod(builder.build())
                .addJavadoc("@类")//类注释
                .build();

        JavaFile javaFile = JavaFile.builder("com.example.apt", typeSpec).build();//设置包名
        try {
            javaFile.writeTo(filer);//生成java文件   路径 在 app module/build/generated/source/apt
            messager.printMessage(Diagnostic.Kind.NOTE,"print: create JavaFile");
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return true;
    }
}

最后build一下生成java文件


©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,974评论 6 342
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,687评论 25 708
  • 用两张图告诉你,为什么你的 App 会卡顿? - Android - 掘金 Cover 有什么料? 从这篇文章中你...
    hw1212阅读 12,997评论 2 59
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,026评论 19 139
  • 夏末的午后阳光慵懒地照进房间空气组合成绚丽的色彩是我流淌着的梦我的梦流淌着悬浮于空中的楼宇之上白云的照影轻盈,空灵...
    简JN阅读 1,941评论 47 62