2010-01-18 49 views
3

資源包和MessageFormat可能具有以下結果嗎?在.properties文件中爲MessageFormat測試null參數

  • 當我打電話getBundle("message.07", "test")得到"Group test"
  • 當我打電話getBundle("message.07", null)得到"No group selected"

我在網上找到的每一個例子是行星,與磁盤等文件。

我只需要檢查資源包的屬性文件中是否有一個參數是null或不存在)。我希望找到一個特殊的空參數格式,如{0,choice,null#No group selected|notnull#Group {0}}

的方法我用得到的包是:

public String getBundle(String key, Object... params) { 
    try { 
    String message = resourceBundle.getString(key); 
    if (params.length == 0) { 
     return message; 
    } else { 
     return MessageFormat.format(message, params); 
    } 
    } catch (Exception e) { 
    return "???"; 
    } 
} 

我也呼籲其他bundle這種方法,像

  • getBundle("message.08", 1, 2) =>"Page 1 of 2"(總參數,無需檢查null
  • getBundle("message.09") =>"Open file"(無參數,無需檢查null

我應該在我的.properties文件中寫入message.07來描述結果?
我現在擁有的是:

message.07=Group {0} 
message.08=Page {0} of {1} # message with parameters where I always send them 
message.09=Open file   # message without parameters 
+0

檢查我的編輯。 – 2010-01-19 03:13:08

+0

看來我的問題的答案是沒有特殊的格式來傳遞給'MessageFormat'來檢查參數是否爲'null'。 – 2010-01-19 11:50:05

回答

0

.properties文件,

message.07=Group {0} 
message.08=Page {0} of {1} 
message.09=Open file 
message.null = No group selected 

然後你需要改變你的代碼放在一個明確的檢查paramsnull。如果null那麼你可以做一些像resourceBundle.getString(NULL_MSG)。其中NULL_MSG就是這樣,

private static final String NULL_MSG = "message.null"; 

所以,現在你的原始方法會變成這樣。

public String getBundle(String key, Object... params) { 
    String message = null; 
    try { 
    if (params == null) { 
     message = resourceBundle.getString(NULL_MSG); 
    } else { 
     message = MessageFormat.format(resourceBundle.getString(key), params); 
    } 
    } catch (Exception e) { 
    e.printStackTrace(); 
    } 
    return message; 
} 

調用我的方法如下圖所示,

getBundle("message.07", "test") // returning 'Group test' 
getBundle("message.07", null) // returning 'No group selected' 
getBundle("message.08", 1, 2) // returning 'Page 1 of 2' 
getBundle("message.08", null) // returning 'No group selected' 
getBundle("message.09", new Object[0]) // returning 'Open file' 
getBundle("message.09", null) // returning 'No group selected' 

現在告訴我問題出在哪裏?

+0

我不想改變這種方法,因爲它在我的代碼中隨處可見,它應該與其餘的消息一起工作(參數是數字,字符串...),我不需要檢查' null'。也有可能有更多這樣的情況(更多消息與空測試) – 2010-01-18 11:43:50

+0

它不會破壞任何地方的代碼,只是改變內部行爲。參數不改變,既不是返回類型。我沒有看到任何問題。 – 2010-01-18 12:26:25

+0

您不需要每個消息的補充密鑰。只需爲'null'製作一個通用的。這足夠了,AFAICS。此外,請檢查我的編輯。 – 2010-01-19 02:59:43

1

我會建議不要嘗試改變包的功能(即使你有一個getBundle方法封裝它)。

根本就在你的代碼:

getBundle(param == null? "message.07.null": "message.07", param) 

,或進行另一個方法:

getBundleOrNull("message.07", param, "message.07.null") 

,做

public String getBundleOrNull(String key, value, nullKey) { 
    return getBundle(value == null? nullKey: key: value); 
} 
+0

謝謝你的回答。我會選擇將你的答案和Vinegear的結合起來,這很難選擇一個被接受的答案。無論如何,我會投你的答案。 – 2010-01-19 11:46:42

+0

謝謝。祝你好運! – helios 2010-01-19 12:02:07

相關問題