如何使用 JavaParser 在新行上添加注释?

问题描述

我想使用 javaparser 为字段添加注释。

public static String annotate() {
    String classstring = new StringJoiner("\n")
            .add("class A {")
            .add("")
            .add("  @ExistingAnnotation")
            .add("  private int i;")
            .add("")
            .add("}")
            .toString();

    compilationunit cu = StaticJavaParser.parse(classstring);
    LexicalPreservingPrinter.setup(cu);

    cu.findFirst(FieldDeclaration.class).get()
            .addAnnotation("Annotation")
            .addAnnotation(Nonnull.class)
            .addMarkerAnnotation("MarkerAnnotation");

    return LexicalPreservingPrinter.print(cu);
}

但与我期望的相反,添加的注释没有放在自己的行上,而是附加到同一行上的现有注释

import javax.annotation.Nonnull;

class A {

  @ExistingAnnotation @Annotation() @Nonnull() @MarkerAnnotation
  private int i;

}

我想要

  @ExistingAnnotation
  @Annotation()
  @Nonnull()
  @MarkerAnnotation
  private int i;

这可能吗?

解决方法

尝试打印:

new DefaultPrettyPrinter().print(cu);