一、创建一个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文件