格式化Java文件

本文介绍了使用Eclipse默认设置创建代码格式化器的方法,并展示了如何自动格式化Java代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值