测试代码
public class JavaFormatter {
private static CodeFormatter formatter =null;
public static synchronized CodeFormattergetFormatter() {
if (formatter == null) {
Map<String,String> hashMap = new HashMap<String,String>();
hashMap.put(JavaCore.COMPILER_SOURCE, "1.5");
hashMap.put(JavaCore.COMPILER_COMPLIANCE, "1.5");
hashMap.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, "1.5");
formatter =ToolFactory.createCodeFormatter(hashMap);
}
return formatter;
}
public static String defaultFormat(Stringsource) {
TextEdit edit =getFormatter().format(CodeFormatter.K_COMPILATION_UNIT, source, 0,source.length(), 0, null);
if (edit == null) {
returnsource;
}
IDocument doc = newDocument();
doc.set(source);
try {
edit.apply(doc);
} catch (Exception e) {
returnsource;
}
return doc.get();
}
}
效果
pom文件
<dependency>
<groupId>org.eclipse.jdt</groupId>
<artifactId>core</artifactId>
<version>3.2.0.666</version>
</dependency>
<dependency>
<groupId>org.eclipse</groupId>
<artifactId>text</artifactId>
<version>3.2.0-v20060605-1400</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.eclipse.core</groupId>
<artifactId>runtime</artifactId>
<version>3.2.0-v20060603</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.eclipse.equinox</groupId>
<artifactId>common</artifactId>
<version>3.2.0-v20060603</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.floggy.3rd.org.eclipse.core</groupId>
<artifactId>resources</artifactId>
<version>3.3.1.R33x_v20080205</version>
</dependency>
<dependency>
<groupId>org.eclipse</groupId>
<artifactId>osgi</artifactId>
<version>3.5.0.v20090520</version>
</dependency>