我想制作自己的Annotation,我希望它能创建.java文件。为此,我使用
@Retention(RetentionPolicy.CLASS)
但是,我无法理解如何在处理器中触发处理器和init方法?我想它必须在编译时创建.java文件。但它没有。如何触发Annotation创建.java文件?
我在Android工作室做了一切,我改变了gradle来编译这个像java。
这是处理器代码:
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
for (Element annotatedElement : roundEnv.getElementsAnnotatedWith(Factory.class)) {
if (annotatedElement.getKind() != ElementKind.CLASS) {
error(annotatedElement, "Only classes can be annotated with @%s", Factory.class.getSimpleName());
return true;
}
TypeElement typeElement = (TypeElement) annotatedElement;
try {
FactoryAnnotatedClass annotatedClass = new FactoryAnnotatedClass(typeElement);
if (!isValidClass(annotatedClass)) {
return true;
}
FactoryGroupedClasses factoryClass = factoryClasses.get(annotatedClass.getQualifiedFactoryGroupName());
if (factoryClass == null) {
String qualifiedGroupName = annotatedClass.getQualifiedFactoryGroupName();
factoryClass = new FactoryGroupedClasses(qualifiedGroupName);
factoryClasses.put(qualifiedGroupName, factoryClass);
}
factoryClass.add(annotatedClass);
} catch (IllegalArgumentException e) {
error(typeElement, e.getMessage());
return true;
} catch (IdAlreadyUsedException e) {
FactoryAnnotatedClass existing = e.getExisting();
// Already existing
error(annotatedElement,
"Conflict: The class %s is annotated with @%s with id ='%s' but %s already uses the same id",
typeElement.getQualifiedName().toString(), Factory.class.getSimpleName(),
existing.getTypeElement().getQualifiedName().toString());
return true;
}
}
try {
for (FactoryGroupedClasses factoryClass : factoryClasses.values()) {
factoryClass.generateCode(elementUtils, filer);
}
factoryClasses.clear();
} catch (IOException e) {
error(null, e.getMessage());
}
return true;
}
@Override
public synchronized void init(ProcessingEnvironment processingEnv) {
super.init(processingEnv);
typeUtils = processingEnv.getTypeUtils();
elementUtils = processingEnv.getElementUtils();
filer = processingEnv.getFiler();
messager = processingEnv.getMessager();
}