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