MessageFormat 以模式字串 (Pattern) 為核心,支援區域無關的訊息格式化。模式由 FormatElement 組成:
{ArgumentIndex}
{ArgumentIndex, FormatType}
{ArgumentIndex, FormatType, FormatStyle}
{ArgumentIndex, FormatType, SubformatPattern} // 子格式模式 (如 #.##)
| FormatType | 對應 Formatter | FormatStyle 範例 |
|---|---|---|
| number | NumberFormat | integer, currency, percent, #.## (子模式) |
| date | DateFormat | short, medium, long, full |
| time | DateFormat | short, medium, long, full |
| choice | ChoiceFormat | 複雜區間匹配模式 |
String msg = "{0}{1}{2}{3}{4}{5}{6}{7}{8}";
Object[] args = {"A","B","C","D","E","F","G","H","I"};
System.out.println(MessageFormat.format(msg, args)); // ABCDEFGHI
'' → 輸出單引號 '' (單個) → 吞噬後續字元直到下一個單引號,包含占位符!MessageFormat.format("oh, {0} is 'a' pig", "ZhangSan");
// 輸出: oh, ZhangSan is a pig (a 被單引號包裹,但單引號消失)
MessageFormat.format("oh, {0} is ''a'' pig", "ZhangSan");
// 輸出: oh, ZhangSan is 'a' pig (雙單引號轉義為一個)
MessageFormat.format("'{0}{1}'", 1, 2);
// 輸出: {0}{1} (整個被單引號包裹,占位符失效)
MessageFormat.format("'{0}'-{1}", 1, 2);
// 輸出: {0}-2 (只有 {0} 失效)
{ (左大括號) 必須用單引號包裹:'{',否則拋 IllegalArgumentException。} (右大括號) 可直接使用。MessageFormat.format("'{'{0}}", "X-rapido"); // 輸出: {X-rapido}
MessageFormat.format("oh, }} is good", "d"); // 輸出: oh, }} is good
// 數字保留一位小數
MessageFormat.format("oh, {0,number,#.#} is good", 3.1415); // oh, 3.1 is good
// 貨幣格式 (依 Locale)
MessageFormat.format("Price: {0,number,currency}", 1234.5); // Price: $1,234.50 (US Locale)
// 日期時間
MessageFormat.format("Date: {0,date,long}, Time: {0,time,short}", new Date());
MessageFormat.format(pattern, args) 靜態方法內部 每次都 new 新實例,高頻呼叫會造成 GC 壓力。
// ❌ 低效:每次新建實例
for (String name : names) {
String msg = MessageFormat.format("Hello {0}", name);
}
// ✅ 高效:重用實例
MessageFormat mf = new MessageFormat("Hello {0}");
for (String name : names) {
String msg = mf.format(new Object[]{name});
}
{ 時寫 '{';輸出 ' 寫 ''。java.text 專用 Formatter 或現代 String.format/MessageFormat 混用。