[英]Write a java file using JavaPoet in annotation processor
我正在嘗試使用 processingEnv.getFiler() 創建源文件。 但我沒有看到任何源文件被創建。 下面是我正在使用的代碼:
public void javaPoetEg() {
Filer filer = super.processingEnv.getFiler();
MethodSpec main = MethodSpec.methodBuilder("testFiler")
.addModifiers(Modifier.PUBLIC)
.returns(void.class)
.addParameter(String[].class, "args")
.addStatement("$T.out.println($S)", System.class, "Hello, JavaPoet!")
.build();
TypeSpec helloWorld = TypeSpec.classBuilder("HelloWorld")
.addModifiers(Modifier.PUBLIC, Modifier.FINAL)
.addMethod(main)
.build();
JavaFile javaFile = JavaFile.builder("com.ankit.annotation", helloWorld)
.build();
try{
javaFile.writeTo(filer);
} catch (IOException e) {
e.printStackTrace();
}
}
然后在 Annotation 處理器的重寫函數 process() 中調用函數 javaPoetEg。 我在這里做錯了什么?
我建議你看看Filer
應該如何工作。 Javadoc
源文件的位置可能取決於您通過命令行指定的參數,或者您必須檢查默認generated
目錄。
這部分: javaFile.writeTo
寫入File
或PrintStream
。 所以你可以做這樣的事情:
File file = new File("/target/directory");
javaFile.writeTo(file); // this will make a new File with all the data you added
或者:
javaFile.writeTo(System.out) // this will print the file representation in the console
希望這可以幫助。 干杯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.