【问题标题】:How to put annotations on a new line with JavaParser?如何使用 JavaParser 将注释放在新行上?
【发布时间】:2021-03-18 20:31:52
【问题描述】:

我想用 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;

这可能吗?

【问题讨论】:

    标签: java annotations javaparser


    【解决方案1】:

    尝试打印:

    new DefaultPrettyPrinter().print(cu);
    

    【讨论】:

    • LexicalPreservingPrinter 无法知道如何打印新注释,但漂亮的打印机使用自己的格式规则打印。 cu.toString() 使用漂亮的打印机
    猜你喜欢
    • 2022-12-18
    • 1970-01-01
    • 2014-06-19
    • 2016-09-26
    • 2018-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多