Created
March 5, 2015 02:31
-
-
Save pfmiles/653c8b59e795698c867d to your computer and use it in GitHub Desktop.
调用eclipse jdt core对生成的java源码进行格式化
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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