调用JDT进行格式化代码

来源:互联网 发布:智能化系统集成软件 编辑:程序博客网 时间:2024/06/06 01:10
原文地址:调用JDT进行格式化代码作者:纯粹

测试代码
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();
 }
}

 

效果

[转载]调用JDT进行格式化代码

 

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>

0 0
原创粉丝点击