java.text.MessageFormat的用法
Java.text.MessageFormat 用法详解与替代方案
MessageFormat 基本用法
MessageFormat是 Java 标准库中用于处理参数化消息的类,特别适合国际化场景:
核心功能
支持位置参数:
{0},{1},{2}...支持数据类型格式化:数字、日期、时间等
支持选择格式(ChoiceFormat):根据数值显示不同文本
基本示例
import java.text.MessageFormat;
import java.util.Date;public class MessageFormatDemo {public static void main(String[] args) {// 简单字符串格式化String pattern1 = "Hello {0}, today is {1}";String result1 = MessageFormat.format(pattern1, "Alice", new Date());System.out.println(result1);// 输出: Hello Alice, today is 2023-07-15// 数字格式化String pattern2 = "Price: {0,number,currency}";String result2 = MessageFormat.format(pattern2, 19.99);System.out.println(result2);// 输出: Price: $19.99// 日期格式化String pattern3 = "Date: {0,date,full}";String result3 = MessageFormat.format(pattern3, new Date());System.out.println(result3);// 输出: Date: Saturday, July 15, 2023// 选择格式String pattern4 = "You have {0,choice,0#no files|1#one file|1<{0} files}";System.out.println(MessageFormat.format(pattern4, 0)); // You have no filesSystem.out.println(MessageFormat.format(pattern4, 1)); // You have one fileSystem.out.println(MessageFormat.format(pattern4, 5)); // You have 5 files}
}优点
内置于 Java 标准库
支持复杂格式化(日期、数字、选择)
与 ResourceBundle 集成良好,适合国际化
缺点
语法较复杂(特别是选择格式)
性能不如更简单的格式化方法
不支持命名参数
错误处理不够友好
更好的替代方案
1. String.format()(Java 5+)
更简单直接的格式化方法:
String result = String.format("Hello %s, today is %tF", "Alice", new Date());
// 输出: Hello Alice, today is 2023-07-15优点:
语法更简洁(类似C的printf)
性能更好
支持基本数据类型格式化
缺点:
不支持选择格式
国际化支持不如MessageFormat
2. java.text.MessageFormat 的增强版
// 使用Map实现命名参数(自定义工具方法)
import java.util.HashMap;
import java.util.Map;public class EnhancedMessageFormat {public static String format(String pattern, Map<String, Object> params) {for (Map.Entry<String, Object> entry : params.entrySet()) {pattern = pattern.replace("{" + entry.getKey() + "}", entry.getValue().toString());}return pattern;}public static void main(String[] args) {String pattern = "Hello {name}, your balance is {balance}";Map<String, Object> params = new HashMap<>();params.put("name", "Alice");params.put("balance", 1000.50);System.out.println(format(pattern, params));// 输出: Hello Alice, your balance is 1000.5}
}3. Apache Commons Lang - StringSubstitutor(推荐)
更现代、更灵活的解决方案:
import org.apache.commons.lang3.text.StringSubstitutor;
import java.util.HashMap;
import java.util.Map;public class StringSubstitutorDemo {public static void main(String[] args) {Map<String, Object> values = new HashMap<>();values.put("name", "Alice");values.put("balance", 1000.50);values.put("date", new Date());String template = "Hello ${name}, your balance is ${balance}, today is ${date}";String result = StringSubstitutor.replace(template, values);System.out.println(result);}
}优点:
命名参数(${param})
简单直观的语法
支持默认值(${name:-default})
支持递归替换
更好的性能
4. Spring Framework 的 MessageSource
对于 Spring 应用的最佳解决方案:
import org.springframework.context.MessageSource;
import org.springframework.context.support.ResourceBundleMessageSource;public class SpringMessageDemo {public static void main(String[] args) {ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();messageSource.setBasename("messages");Object[] params = {"Alice", new Date()};String message = messageSource.getMessage("greeting", params, Locale.US);System.out.println(message);}
}// messages.properties 文件内容:
// greeting=Hello {0}, today is {1,date,full}优点:
完善的国际化支持
与 Spring 生态无缝集成
支持参数化消息
支持消息缓存提高性能
选择建议
简单场景:使用
String.format()需要命名参数:使用 Apache Commons Lang 的
StringSubstitutorSpring 应用:使用 Spring 的
MessageSource复杂国际化需求:保留使用
MessageFormat(特别是与 ResourceBundle 配合时)
对于大多数现代 Java 应用,Apache Commons Lang 的 StringSubstitutor提供了最佳平衡点:语法简洁、功能强大、性能良好,且不需要依赖完整的框架。
