Formatting Java Code

I use FreeMarker to generate java code, but since most of it is dynamically generated, it is difficult to control the generation of the code.

I want the code to be well formatted. Does anyone know lib or something like a beautiful printer for Java code?

+5
source share
9 answers

I assume I will use the Eclipse CodeFormatter, just like this guy: http://ssscripting.wordpress.com/2009/06/10/how-to-use-the-eclipse-code-formatter-from-your -code /

UPDATE: finished using jastyle ( http://sourceforge.net/projects/jastyle/ ). here is an example:

public static String formatJavaCode(String code) throws Exception {
    ASFormatter formatter = new ASFormatter();

    // bug on lib implementation. reported here: http://barenka.blogspot.com/2009/10/source-code-formatter-library-for-java.html
    code.replace("{", "{\n");

    Reader in = new BufferedReader(new StringReader(code));
    formatter.setJavaStyle();
    in.close();
    return FormatterHelper.format(in,formatter);
}
0

Google java format . https://github.com/google/google-java-format

maven google-java-format-0.1-SNAPSHOT.jar / java -jar google-java-format-0.1-SNAPSHOT.jar, .

+2
+1

Jalopy . CLI . Japlopy Console Plugin

+1

, .java Eclipse. , , .

0

FreeMarker Java. : https://source.mysema.com/svn/mysema/projects/codegen/trunk/

, API, . :

    JavaWriter writer = new JavaWriter(new StringWriter());   
    writer.beginClass("FieldTests");
    writer.privateField("String", "privateField");
    writer.privateStaticFinal("String", "privateStaticFinal", "\"val\"");
    writer.protectedField("String","protectedField");
    writer.field("String","field");
    writer.publicField("String","publicField");
    writer.publicStaticFinal("String", "publicStaticFinal", "\"val\"");
    writer.publicFinal("String", "publicFinalField");
    writer.publicFinal("String", "publicFinalField2", "\"val\"");        
    writer.end();

public class FieldTests {

    private String privateField;

    private static final String privateStaticFinal = "val";

    protected String protectedField;

    String field;

    public String publicField;

    public static final String publicStaticFinal = "val";

    public final String publicFinalField;

    public final String publicFinalField2 = "val";

}

codegen Querydsl, Java . . FreeMarker . , Java, .

Codegen. , FreeMarker .

0

- eclipse java IDE ctrl + f . .

0

For standalone command line tools with many configuration options to suit your code formatting style, you can try:

They are both free, open source and can format not only Java source code (C, C ++, C #, etc.)

0
source

All Articles