如何在方法之后插入新行并使用Eclipse JDT代码格式化器键入注释?

时间:2015-02-01 19:24:33

标签: 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字段,在所有注释后添加新行,甚至是方法参数注释。但我想在类型方法或类型注释之后添加换行符

Edit:

这是格式化代码:

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

1 个答案:

答案 0 :(得分:1)

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。它可以在我面前的日食4.4.0

中找到