Question: 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?

Answer: 
Jalopy works beautifully. You can use it's CLI for standalone usage. [Japlopy Console Plugin](http://jalopy.sourceforge.net/existing/plugin-console.html)
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](http://www.querydsl.com/) 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.