Java注释处理器未在生成的源中生成文件

问题描述 投票:0回答:1

我正在编写一个简单的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文件夹中?

我正在编写一个简单的Java注释处理器,该处理器使用JavaPoet生成Java类,然后将其写入文件管理器。 @AutoService(Processor.class)公共类ConfigProcessor扩展了...

java java-annotations
1个回答
0
投票

我有完全相同的问题,解决方案看起来很奇怪。如果仅通过设置属性来配置maven-compiler-plugin,它总是直接在目标/类中生成源代码,但是当我在“插件”部分中明确定义maven-compiler-plugin时,我的代码将在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>
© www.soinside.com 2019 - 2024. All rights reserved.