Java代码格式

我正在使用FreeMarker生成java代码,但由于大多数是动态生成的,因此很难控制代码的形成。

我希望代码格式化得很好。 有没有人知道lib或类似于java代码的漂亮打印机?

您可以使用Eclipse或Jalopy代码格式化程序重新格式化生成的代码。

您可以运行像astyle这样的格式化程序

Jalopy工作得很漂亮。 您可以使用它的CLI进行独立使用。 Japlopy控制台插件

Google java格式非常适合我。 https://github.com/google/google-java-format

在maven构建之后,在core / target文件夹中找到google-java-format-0.1-SNAPSHOT.jar,然后尝试使用java -jar google-java-format-0.1-SNAPSHOT.jar查看使用信息。

我想我会使用Eclipse的CodeFormatter,就像这个人一样: http ://ssscripting.wordpress.com/2009/06/10/how-to-use-the-eclipse-code-formatter-from-your-code/

更新:最终使用jastyle( http://sourceforge.net/projects/jastyle/ )。 这是一个例子:

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

您可以在Eclipse中编辑.java文件时对其进行格式化。 如果不编辑它,它是否格式化并不重要。

我从FreeMarker切换到我自己的Java源代码生成实用程序。 可以从这里访问来源: https : //source.mysema.com/svn/mysema/projects/codegen/trunk/

它的设计方式使您只需调用API并且输出格式正确。 这是一个例子:

  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(); 

哪个变成了

 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"; } 

我为Querydsl开发了codegen实用程序, 它将 Java域类型镜像为查询类型。 因此序列化需求非常复杂。 使用FreeMarker模板简单无法扩展。 输出中的定制过多,在Java中控制比模板语言语法更好。

这不是Codegen模块的广告。 我只想指出,对于高度可定制的序列化,FreeMarker可能无法扩展。

最简单的方法是将您的代码粘贴到eclipse java IDE中,并在您选择的代码上执行ctrl + f。 这将以易读的forms格式化您的代码。