简体   繁体   English

在注解处理器中使用 JavaPoet 编写一个 java 文件

[英]Write a java file using JavaPoet in annotation processor

I am trying to use processingEnv.getFiler() to create a source file.我正在尝试使用 processingEnv.getFiler() 创建源文件。 But I don't see any source file getting created.但我没有看到任何源文件被创建。 Below is the code that I am using:下面是我正在使用的代码:

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();
  }
}

And then calling the function javaPoetEg in the overridden function process() of Annotation processor.然后在 Annotation 处理器的重写函数 process() 中调用函数 javaPoetEg。 What am I doing wrong here?我在这里做错了什么?

I suggest you take a look at how Filer is supposed to work.我建议你看看Filer应该如何工作。 Javadoc Javadoc
The location of the source files might depends on parameters you specify via command line, or, you have to check the default generated directory.源文件的位置可能取决于您通过命令行指定的参数,或者您必须检查默认generated目录。

This part: javaFile.writeTo writes to a File , or a PrintStream .这部分: javaFile.writeTo写入FilePrintStream So you can do something like this:所以你可以做这样的事情:

File file = new File("/target/directory");
javaFile.writeTo(file); // this will make a new File with all the data you added

Or:或者:

javaFile.writeTo(System.out) // this will print the file representation in the console

Hope this helps.希望这可以帮助。 Cheers.干杯。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM