10

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?

4

1 回答 1

4

如果你想从你自己的 java 代码中使用 Eclipse 格式化程序,我建议你看看maven java formatter plugin

它是一个 maven 插件,可用于根据 Eclipse 代码格式化设置文件对源代码进行格式化。

如果您不想使用 maven 但想将格式化代码嵌入到您自己的代码中,请查看FormatterMojo。它包含启动 Eclipse Code Formatter 的代码(使用 Eclipse 库)

这一切都是免费和开源的。

于 2013-02-09T13:22:49.647 回答