0

I want to add an annotation to a field with 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);
}

But contrary to what I expect the added annotation is not put on its own line but appended to the existing annotation on the same line

import javax.annotation.Nonnull;

class A {

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

}

Instead I want

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

Is that possible?

peer
  • 4,171
  • 8
  • 42
  • 73

1 Answers1

0

Try to print with:

new DefaultPrettyPrinter().print(cu);
Rangel Preis
  • 394
  • 1
  • 7
  • LexicalPreservingPrinter has no way of knowing how to print the new annotations, but the pretty printer prints with its own formatting rules. cu.toString() uses pretty printer – jpl Jul 24 '21 at 08:23