我注意到eclipse indenter支持最新版本的java,如果我可以使用该类来缩进生成的java源代码,那就太好了。有没有办法整合它?
编辑:我需要能够在代码中包含代码格式化程序。没有外部电话。
EDIT2:我设法让它运转起来。你可以阅读故事here。谢谢VonC!
答案 0 :(得分:5)
您可以尝试将格式化程序作为standalone application(也是detailed here)运行。
eclipse -vm <path to virtual machine> -application org.eclipse.jdt.core.JavaCodeFormatter [ OPTIONS ] <files>
首先尝试使用eclipse IDE定义格式设置以获得正确的结果,然后导出这些设置,并在eclipse.exe参数中使用该配置文件。
或者另见"Generating a Config File for the Formatter Application"
eclipse [...] -config <myExportedSettings>
在java程序中,您可以尝试直接格式化:
CodeFormatter
format(aString)
来格式化aString。它将返回格式化的字符串。感谢Geo他自己和his blog entry中的报告,我现在知道您需要使用DefaultCodeFormatter
String code = "public class geo{public static void main(String[] args){System.out.println(\"geo\");}}";
CodeFormatter cf = new DefaultCodeFormatter();
TextEdit te = cf.format(CodeFormatter.K_UNKNOWN, code, 0,code.length(),0,null);
IDocument dc = new Document(code);
try {
te.apply(dc);
System.out.println(dc.get());
} catch (MalformedTreeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadLocationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
再次,博客条目中的完整详细信息。感谢Geo的反馈!
Thorbjørn Ravn Andersen提及in the comments:
Maven2 Java Formatter Plugin v0.4描述了一个允许Maven调用Eclipse格式化程序的maven插件 从0.4开始,它调用Eclipse 3.5,它不支持Java 8。
答案 1 :(得分:1)
实际上,VonC的答案有一个问题:DefaultCodeFormatter位于“内部”包中,因此客户不应该使用它!
我最近在stackoverflow上问了同样的问题,并提出了the answer a little while later。
简而言之,您需要使用ToolFactory,如
ToolFactory.createCodeFormatter(null);
答案 2 :(得分:0)
我在一个独立于Eclipse的项目中使用CodeFormatter
。调用ToolFactory.createCodeFormatter(null);
时使用的默认选项无法处理源代码 - format()
调用的结果为空。
最小工作选项设置如下:
Hashtable<String, String> options = new Hashtable<>();
options.put("org.eclipse.jdt.core.compiler.codegen.targetPlatform", "1.8");
options.put("org.eclipse.jdt.core.compiler.compliance", "1.8");
options.put("org.eclipse.jdt.core.compiler.source", "1.8");
CodeFormatter codeFormatter = ToolFactory.createCodeFormatter(options);