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

```
For standalone command-line tools with plenty of configuration options to fit your code formatting style, you can try:

* [astyle](http://astyle.sourceforge.net/)
* [ClangFormat](https://clang.llvm.org/docs/ClangFormat.html)

They are both free, open-source, and can format more than just Java source code (C, C++, C#, etc.)