萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Java MessageFormat 格式化完整指南:語法、陷阱與效能優化

MessageFormat 核心語法

MessageFormat 以模式字串 (Pattern) 為核心,支援區域無關的訊息格式化。模式由 FormatElement 組成:

{ArgumentIndex}
{ArgumentIndex, FormatType}
{ArgumentIndex, FormatType, FormatStyle}
{ArgumentIndex, FormatType, SubformatPattern}  // 子格式模式 (如 #.##)

FormatType 與 FormatStyle 對照

FormatType對應 FormatterFormatStyle 範例
numberNumberFormatinteger, currency, percent, #.## (子模式)
dateDateFormatshort, medium, long, full
timeDateFormatshort, medium, long, full
choiceChoiceFormat複雜區間匹配模式

實戰範例集錦

1. 多參數基本替換 (索引可超過 9)

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

2. 單引號轉義規則 (最易踩坑)

  • '' → 輸出單引號 '
  • ' (單個) → 吞噬後續字元直到下一個單引號,包含占位符!
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} 失效)

3. 大括號處理

  • { (左大括號) 必須用單引號包裹:'{',否則拋 IllegalArgumentException。
  • } (右大括號) 可直接使用。
MessageFormat.format("'{'{0}}", "X-rapido"); // 輸出: {X-rapido}
MessageFormat.format("oh, }} is good", "d");  // 輸出: oh, }} is good

4. 數字/日期格式化

// 數字保留一位小數
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 實例

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

最佳實踐總結

  1. 模式字串中 單引號務必成對,否則會吞噬占位符。
  2. 需輸出 { 時寫 '{';輸出 ' 寫 ''。
  3. 高頻格式化場景 務必重用實例。
  4. 複雜格式化需求優先考慮 java.text 專用 Formatter 或現代 String.format/MessageFormat 混用。
copyright © 萬盛學電腦網 all rights reserved