[英]Automatically remove the file generated by Java 7 Annotation Processor when delete the annotation in source file
[英]Java annotation processor not generating file in generated sources
我正在编写一个简单的 java 注释处理器,它使用 JavaPoet 生成 java class 然后将其写入文件管理器。
@AutoService(Processor.class)
public class ConfigProcessor extends AbstractProcessor {
private Types typeUtils;
private Elements elementUtils;
private Filer filer;
private Messager messager;
@Override
public synchronized void init(ProcessingEnvironment processingEnv) {
super.init(processingEnv);
typeUtils = processingEnv.getTypeUtils();
elementUtils = processingEnv.getElementUtils();
filer = processingEnv.getFiler();
messager = processingEnv.getMessager();
}
@Override
public Set<String> getSupportedAnnotationTypes() {
Set<String> annotataions = new LinkedHashSet<String>();
annotataions.add(Config.class.getCanonicalName());
return annotataions;
}
@Override
public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latestSupported();
}
@Override
public boolean process(Set<? extends TypeElement> annotations,
RoundEnvironment roundEnv) {
for (Element annotatedElement : roundEnv.getElementsAnnotatedWith(RemoteConfig.class)) {
TypeSpec configImpl = // generating
JavaFile javaFile = JavaFile.builder(elementUtils.getPackageOf(annotatedElement).getQualifiedName().toString(),
configImpl)
.build();
try {
javaFile.writeTo(filer);
} catch (IOException e) {
messager.printMessage(Diagnostic.Kind.ERROR,
"Failed to generate implementation",
annotatedElement);
return true;
}
}
return true;
}
}
此注释处理器将文件保存到target/classes/mypackage
而不是target/generated-sources/annotations/mypackage
我尝试将 maven 编译器插件中的generatedSourcesDirectory
目录设置为生成的源目录,但它仍然在类文件夹中生成它。
如何将生成的类保存在 generated-sources 文件夹中?
我遇到了完全相同的问题,解决方案看起来很奇怪。 如果我仅通过设置属性来配置 maven-compiler-plugin 它总是直接在目标/类中生成源代码,但是当我在插件部分明确定义 maven-compiler-plugin 时,我的代码将在目标/生成源/注释中生成
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
</plugins>
</build>
这是一个可以正常工作的示例,当您删除插件时会出现同样的问题: https://github.com/sockeqwe/annotationprocessing101
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.