在注解处理器中使用JavaPoet编写Java文件

时间:2019-02-10 09:30:00

标签: java annotations java-annotations javapoet

我正在尝试使用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();
  }
}

然后在注释处理器的重写函数process()中调用函数javaPoetEg。我在这里做什么错了?

2 个答案:

答案 0 :(得分:0)

我建议您看看Filer应该如何工作。 Javadoc
源文件的位置可能取决于您在命令行中指定的参数,或者必须检查默认的generated目录。

答案 1 :(得分:0)

这部分:javaFile.writeTo写入FilePrintStream。因此,您可以执行以下操作:

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

希望这会有所帮助。干杯。