I'm using FreeMarker to generate java code, but as most of it is dynamically generated it's difficult to control the code formation.
I want to get code well formatted. Does anyone knows a lib or something like a pretty printer for java code?
I'm using FreeMarker to generate java code, but as most of it is dynamically generated it's difficult to control the code formation.
I want to get code well formatted. Does anyone knows a lib or something like a pretty printer for java code?
Jalopy works beautifully. You can use it's CLI for standalone usage. Japlopy Console Plugin
I guess i will use Eclipse's CodeFormatter, just like this guy: http://ssscripting.wordpress.com/2009/06/10/how-to-use-the-eclipse-code-formatter-from-your-code/
UPDATE: ended up using jastyle ( http://sourceforge.net/projects/jastyle/ ). here's an example:
public static String formatJavaCode(String code) throws Exception {
ASFormatter formatter = new ASFormatter();
// bug on lib's 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);
}
You can format it when you edit the .java file in Eclipse. When you don't edit it, it doesn't matter if it is formatted or not.
I switched from FreeMarker to my own Java source code generation utility. The sources are accessible from here : https://source.mysema.com/svn/mysema/projects/codegen/trunk/
It is designed in such a way that you just call the API and the output is properly formatted. Here is an example :
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();
Which turns into
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";
}
I developed the codegen utility for Querydsl which mirrors Java domain types into query types. So the serialization needs are very complex. Using FreeMarker templates simple didn't scale. There was too much customization in the output, which is better to control in Java than a template language syntax.
This is not an advertisement for the Codegen module. I just wanted to make the point that for highly customizable serialization FreeMarker might not scale.