Java – use the eclipse code formatter from your own program

Recently I wrote some tools to help me generate java code, otherwise it will be a long and tedious task I use freemaker to write templates However, all spaces in the template remain in the output, resulting in fairly complex code I can remove indentation from my template to solve this problem, but doing so makes my template unmaintainable

Consider this simple example template:

public class MyTestClass
{
    <#list properties as p>
        private String ${p.name};
    </#list>
}

My template format is good, but my code is as follows:

public class MyTestClass
{
        private String prop1;
        private String prop2;
        private String prop3;
}

The indentation is a little too much. It should be:

public class MyTestClass
{
    private String prop1;
    private String prop2;
    private String prop3;
}

To do this, I must remove indents from my template:

public class MyTestClass
{
    <#list properties as p>
    private String ${p.name};
    </#list>
}

For this simple case, removing indents from my template is not a problem, but you can imagine that complex templates become very difficult to read

On the one hand, I really hope my code format is good, but on the other hand, I also hope my template format is good I use eclipse as the IDE, and the built - in formatter is completely customized according to my (and my team's) wishes It would be huge if I could somehow generate code from freemaker templates and format its output into an eclipse formatter in subsequent processing steps

I can run the formatter manually after generating the code, but I really want to automate this process

So, novel, does anyone know that I can use eclipse's code formatter in my own java code?

Solution

If you want to use the eclipse formatter from your own java code, I suggest you take a look

It is a maven plug-in that can be used to format source code based on eclipse code format file

If you don't want to use maven, but want to embed the format code into your own code, check formattermojo It contains code to start the eclipse code formatter (using the eclipse Library)

This is free and open source

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>