Recently I wrote some tools that help me generate Java code for what would otherwise be long and tedious tasks. I use freemarker to write up templates. However, all whitespace in the templates is preserved in the output, resulting in quite messy code. I could remove indentation from my templates to fix this, but that makes my templates rather unmaintainable.
Consider this simple example template:
public class MyTestClass
{
<#list properties as p>
private String ${p.name};
</#list>
}
My template is nicely formatted, but my code comes out as this:
public class MyTestClass
{
private String prop1;
private String prop2;
private String prop3;
}
Indentation is a bit too much, it should be:
public class MyTestClass
{
private String prop1;
private String prop2;
private String prop3;
}
To accomplish this, I have to remove indentation from my template like this:
public class MyTestClass
{
<#list properties as p>
private String ${p.name};
</#list>
}
For this simple case it is not really a problem to remove indentation from my template, but you could imagine complex templates to become quite unreadable.
On the one side I really want my code to be nicely formatted, but on the other side I'd like my templates to be nicely formatted as well. I use Eclipse as IDE, with is built-in formatter fully customized to my (and my team's) wishes. It would be great if I could somehow generate code from freemarker templates and as a post processing step format its output with Eclipse's formatter.
I can of course run the formatter manually after generating my code, but I really want to automate this process.
So, long story short, does anyone know how I can use Eclipse's code formatter within my own Java code?
If you want to use the Eclipse formatter from your own java code I suggest you take a look at the maven java formatter plugin.
It's a maven plugin that can be used to format source code based on Eclipse code formatting settings files.
If you don't want to use maven but want to embed the formatting code in your own code, take a look at the FormatterMojo. It contains the code that launches the Eclipse Code Formatter (using the Eclipse libraries)
It's all free and open-source.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With