org.eclipse.jdt.core.formatter.CodeFormatter 用来格式化代码的类
摘录自开源软件源码
private static CodeFormatter getCodeFormatter() {
Map options = DefaultCodeFormatterConstants.getEclipseDefaultSettings();
options.put(JavaCore.COMPILER_COMPLIANCE, JavaCore.VERSION_1_5);
options.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaCore.VERSION_1_5);
options.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_5);
options.put(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ENUM_CONSTANTS, DefaultCodeFormatterConstants.createAlignmentValue(true, DefaultCodeFormatterConstants.WRAP_ONE_PER_LINE,
DefaultCodeFormatterConstants.INDENT_ON_COLUMN));
options.put(DefaultCodeFormatterConstants.FORMATTER_LINE_SPLIT, "160"); //$NON-NLS-1$
CodeFormatter codeFormatter codeFormatter = ToolFactory.createCodeFormatter(options);
return codeFormatter;
}
public static String formatCode(String source) {
TextEdit edit = getCodeFormatter().format(CodeFormatter.K_UNKNOWN, source, 0, source.length(), 0, System.getProperty("line.separator")); //$NON-NLS-1$
if (edit != null) {
IDocument document = new Document(source);
try {
edit.apply(document);
return document.get();
} catch (Exception e) {
VisualSwingPlugin.getLogger().error(e);
}
}
return source;
}
本文介绍了使用Eclipse默认设置创建代码格式化器的方法,并展示了如何自动格式化Java代码。
421

被折叠的 条评论
为什么被折叠?



