Annotation Processing
简称APT,通过注解动态生成必要的类;
使用该技术的有:ButterKnife、EventBus
第一步:创建工程

第二步:复写AbstractProcessor和声明注解处理器

继承AbstractProcessor
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| class MyProcessor : AbstractProcessor() {
lateinit var filer: Filer override fun init(processingEnv: ProcessingEnvironment) { super.init(processingEnv) filer = processingEnv.filer }
override fun process(annotations: MutableSet<out TypeElement>?, roundEnv: RoundEnvironment?): Boolean { return false }
override fun getSupportedAnnotationTypes(): MutableSet<String> { return super.getSupportedAnnotationTypes() }
override fun getSupportedOptions(): MutableSet<String> { return super.getSupportedOptions() }
override fun getSupportedSourceVersion(): SourceVersion { return super.getSupportedSourceVersion() } }
|
声明注解处理器:
mian目录下声明 resources/META-INF/services/javax.annotation.processing.Processor
文件
文件内声明注解处理器类全称:com.benben.lib_processor.MyProcessor
引用:
annotationProcessor project(‘:lib-processor’)
补充:
可以使用 Filer
直接输出文件,也可以使用javapoet
第三方库来输出文件