我正在编写一个简单的Java注释处理器,该处理器使用JavaPoet生成Java类,然后将其写入文件管理器。
@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
目录设置为生成的sources目录,但仍在classes文件夹中生成它。
如何使生成的类保存在generate-sources文件夹中?
答案 0 :(得分:1)
我遇到了完全相同的问题,解决方案看起来很奇怪。如果我仅通过设置属性来配置maven-compiler-plugin,它将始终直接在目标/类中生成源代码,但是当我在plugins部分中显式定义maven-compiler-plugin时,我的代码将在target / generate-sources / annotations < / p>
<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