Skip to content

Instantly share code, notes, and snippets.

@pfmiles
Created March 5, 2015 02:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pfmiles/653c8b59e795698c867d to your computer and use it in GitHub Desktop.
Save pfmiles/653c8b59e795698c867d to your computer and use it in GitHub Desktop.
调用eclipse jdt core对生成的java源码进行格式化
package test;
import java.util.Map;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.ToolFactory;
import org.eclipse.jdt.core.formatter.CodeFormatter;
import org.eclipse.jdt.core.formatter.DefaultCodeFormatterConstants;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.IDocument;
import org.eclipse.text.edits.TextEdit;
/**
* 调用eclipse jdt core对生成的java源码进行格式化
*
* @author pf-miles 2014-4-16 下午2:48:29
*/
public class JavaCodeFormattingUtil {
/**
* 尝试对传入的JavaSourceFile格式化,此操作若成功则将改变传入对象的内容
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public static void tryFormat(JavaSourceFile src) {
Map m = DefaultCodeFormatterConstants.getEclipseDefaultSettings();
m.put(JavaCore.COMPILER_COMPLIANCE, JavaCore.VERSION_1_6);
m.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaCore.VERSION_1_6);
m.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_6);
m.put(DefaultCodeFormatterConstants.FORMATTER_LINE_SPLIT, "160");
m.put(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR, JavaCore.SPACE);
String code = null;
IDocument doc = null;
try {
code = src.getCharContent(true).toString();
CodeFormatter codeFormatter = ToolFactory.createCodeFormatter(m);
TextEdit textEdit = codeFormatter.format(CodeFormatter.K_UNKNOWN, code, 0, code.length(), 0, null);
if (textEdit != null) {
doc = new Document(code);
textEdit.apply(doc);
src.setCode(doc.get());
}
} catch (Exception e) {
throw new RuntimeException("Error occured while formatting code: " + src.toUri(), e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment