java - 如何使用 Eclipse JDT 代码格式化程序在方法和类型注释之后插入新行?

标签 java eclipse eclipse-jdt

我正在使用 Eclipse JDT API 来格式化生成的 java 源文件。 使用哪些选项,我可以强制格式化程序输出如下所示:

@Annotation1 
@Annotation2
@Annotation3
@Annotation4 
public class TheClass {

    private static final int PAGE_SIZE = 10;

    @Annotation5 
    private Object o1;

    @Annotation5 
    private Object o2;


    @Annotation6
    @Annotation7 
    public void doSomething(@Annotation8 @Annotation Object dto) {
         // some works
    }
}

据我所知,DefaultCodeFormatterOptionsinsert_new_line_after_annotation 字段,该字段在所有注释(甚至方法参数注释)之后添加新行。但我想在类型方法或类型注释之后添加换行符

编辑:

这是格式化程序代码:

public String format(String code)
        throws MalformedTreeException, BadLocationException {
    Map options = new java.util.HashMap();
    options.put(JavaCore.COMPILER_SOURCE, "1.5");
    options.put(JavaCore.COMPILER_COMPLIANCE, "1.5");
    options.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, "1.5");

    DefaultCodeFormatterOptions cfOptions =
            DefaultCodeFormatterOptions.getDefaultSettings();
    cfOptions.insert_new_line_after_annotation = false;
    cfOptions.comment_insert_new_line_for_parameter = true;

    cfOptions.blank_lines_before_method = 1;
    cfOptions.number_of_empty_lines_to_preserve= 1;

    cfOptions.tab_char = DefaultCodeFormatterOptions.SPACE;

    CodeFormatter cf = new DefaultCodeFormatter(cfOptions, options);

    TextEdit te = cf.format(CodeFormatter.K_UNKNOWN, code, 0,
            code.length(), 0, null);
    IDocument dc = new Document(code);

    te.apply(dc);
    return dc.get();
}

最佳答案

DefaultCodeFormatterOptions对于注释的每个可能的上下文,注释后都有单独的新行字段

public boolean insert_new_line_after_annotation_on_type;
public boolean insert_new_line_after_annotation_on_field;
public boolean insert_new_line_after_annotation_on_method;
public boolean insert_new_line_after_annotation_on_package;
public boolean insert_new_line_after_annotation_on_parameter;
public boolean insert_new_line_after_annotation_on_local_variable;

所以我猜 insert_new_line_after_annotation_on_type 就是答案...我已经通过 IDE 本身而不是 API 检查了其行为是否符合预期。

这是由 this commit 添加的相对较新的添加内容2014 年 2 月修复 bug/feature 425040 。在我前面的eclipse 4.4.0中可用

关于java - 如何使用 Eclipse JDT 代码格式化程序在方法和类型注释之后插入新行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28266801/

相关文章:

java - 在eclipse中的方法中获取字段类型

java - jSerialComm : failed to open port (Arduino Mega 2560)

android - 在 eclipse galileo 中安装 ADT 8.0.1 的问题

java - Eclipse 使用 Java 9 显示空错误消息

eclipse - 如何从 Eclipse 中现有的 maven 项目创建 git 项目?

java - 在 Eclipse E4 中设置固定零件尺寸

java - 使用 maven 进行增量 java 编译(就像 Eclipse 那样)

java - JPA 为每个请求创建实体管理器工厂?

java - 解析此配置文件的最佳方法是什么?

java - 为什么当有很多请求时应用程序会挂起?