簡體   English   中英

Java 注釋處理器未在生成的源中生成文件

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM