Apt:annotationProcessor

@SupportedOptions(value = {"eventBusIndex","verbose"}):增加自定义参数
build.gradle:
defaultConfig {
     javaCompileOptions {
        annotationProcessorOptions {
             arguments = [eventBusIndex: 'org.greenrobot.eventbusperf.MyEventBusIndex']
         }
    }
}


一.创建java-library的Module:annotation
1.1创建注解类
@Retention(RetentionPolicy.CLASS)
@Target(ElementType.FIELD)
public @interface BindView {
int value();
}

二:创建java-library的Mod:processor:implementation'com.google.auto.service:auto-service:1.0-rc4'
2.1自定义类BindViewProcessor:完成注解解析和生成自定义文件,
@AutoService(Processor.class):Google开发的,用来生成 META-INF/services/javax.annotation.processing.Processor 文件

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

AbstractProcessor主要类和方法
Messager:日志辅助类
Filer:文件辅助类
Elements:元素辅助类
void init(ProcessingEnvironment processingEnv):初始化
public Set getSupportedAnnotationTypes()或@SupportedAnnotationTypes():处理注释类
process:处理核心方法

2.2process处理方式
方式一:拼接string字符串生成辅助类(MainActivity_ViewBind):
JavaFileObject jfo =processingEnv.getFiler().createSourceFile(proxyInfo.getProxyClassFullName(), proxyInfo.getTypeElement());
Writer writer = jfo.openWriter();
writer.write(proxyInfo.generateJavaCode());
writer.flush();
writer.close();

方式二:Poet生成:implementation'com.squareup:javapoet:1.7.0'
JavaFile javaFile = JavaFile.builder(proxyInfo.getPackageName(), proxyInfo.generateJavaCode2()).build();
// 生成文件
    javaFile.writeTo(processingEnv.getFiler());

三.创建Android的Module

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 (Exception e) {
                 e.printStackTrace();
             }
     }
}

你可能感兴趣的:(Apt:annotationProcessor)