Reputation: 342
I am writing a simple java annotation processor which generates a the java class using JavaPoet and then write it into the filer.
@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;
}
}
This annotation processor is saving the files into target/classes/mypackage
instead of target/generated-sources/annotations/mypackage
I have tried setting the generatedSourcesDirectory
directory in the maven compiler plugin to the generated sources directory but it still generates it in the classes folder.
How do I make the generated classes be saved in the generated-sources folder?
Upvotes: 0
Views: 1813
Reputation: 56
I had exactly the same problem and the solution looks quite strange. If I configure maven-compiler-plugin only by setting properties it always generates source code directly in target/classes, but when I explicitly define maven-compiler-plugin in plugins section then my code is generated in target/generated-sources/annotations
<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>
Here's a sample where it works fine and when you remove the plugin the same problem occurs: https://github.com/sockeqwe/annotationprocessing101
Upvotes: 1