簡體   English   中英

如何從注釋處理器獲取 class 代碼作為字符串?

[英]How to get the class code as String from Annotation Processor?

我有一個基本的注釋處理器

@SupportedAnnotationTypes("example.Annotation")
public class Processor extends AbstractProcessor {
    @Override
    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
        for (TypeElement annotation : annotations) {
            Set<? extends Element> elementsAnnotatedWith = roundEnv.getElementsAnnotatedWith(annotation);
            for (Element element : elementsAnnotatedWith) {
                TypeElement typeElement = (TypeElement) element;
                // Here, typeElement.getQualifiedName() is accessible, but not the code nor file path.
            }
        }
        return false;
    }
}

此注解只能用於類。 我知道目標 class 未編譯,因此無法進行反射訪問,但我想將 class 代碼作為字符串以我自己的方式解析,而不是使用此 API。

可能嗎? 我知道我可以獲得限定名稱,但在哪里查找文件?

TypeElement的源代碼可以這樣加載:

private String loadSource(TypeElement typeElement) throws IOException {
    final FileObject source = processingEnv.getFiler().getResource(
        StandardLocation.SOURCE_PATH,
        ((PackageElement) typeElement.getEnclosingElement()).getQualifiedName(),
        typeElement.getSimpleName() + ".java");
    
    try (Reader reader = source.openReader(true)) {
        final StringBuilder builder = new StringBuilder();
        final char[] buf = new char[1024];
        int read;
        while ((read = reader.read(buf)) != -1) {
            builder.append(buf, 0, read);
        }
        return builder.toString();
    }
}

測試的Processor jar 包含一個META-INF/services/javax.annotation.processing.Processor文件,無需指定-process選項:

  • Maven:好的
  • Gradle:需要額外配置,假設src/main/java是源目錄
tasks.withType(JavaCompile) {
    configure(options) {
        options.setSourcepath(project.files('src/main/java'))
    }
}
  • 命令行:添加-sourcepath選項:

javac -cp path/to/processor.jar -sourcepath path/to/sources path/to/JavaFile.java

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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