[英]How can I used named parameters in a messages.properties file?
有沒有辦法讓message.properties記錄如下
message.myMessage=This message is for ${name} in ${location}
而不是
message.myMessage = This message is for {0} in {1}
當我創建消息時,我不一定知道順序/需要多少參數,但我只能按名稱傳遞幾個屬性,並且只使用正確的屬性。
在面對同樣的問題並在源代碼中進行挖掘之后,我發現了一個“循環漏洞”,它可以以一種非常簡單的方式實現:
message.myMessage = This message is for {0,,name} in {1,,location}
這種方法不會消除數字的使用。 使用它的原因是為翻譯人員提供提示。
我恐怕不會,參數是一個Object數組,所以沒有辦法為它們定義名稱。 如果你總是以相同的順序傳入參數數組,盡管你可以像這樣使用它們:
message.myMessage = This message is for {0} in {1}
message.myNameMessage = This message is for {0}
message.myLocationMessage = This message is for people in {1}
message.myAlternateMessage = The message params are location: {1}; name: {0}
看看ICU4J
它允許這樣的事情:
message.myMessage=This message is for {name} in {location}.
並且它比建議的簡單替換更強大,因為可以對參數進行區域設置感知格式化(即:“訂閱到期時間:{expirationDate,date,long})
http://icu-project.org/apiref/icu4j/com/ibm/icu/text/MessageFormat.html
對於那些嘗試過的人來說,一切皆有可能......我從來沒有聽說過類似Java的東西,但你可以自己寫。
請看一下這個例子:
public String format(String message, String... arguments) {
for (String argument : arguments) {
String[] keyValue = argument.split("=");
if (keyValue.length != 2)
throw new IllegalArgumentException("Incorrect argument: " + argument);
String placeholder = "${" + keyValue[0] + "}";
if (!message.contains(placeholder))
throw new IllegalArgumentException(keyValue[0] + " does not exists.");
while (message.contains(placeholder))
message = message.replace(placeholder, keyValue[1]);
}
return message;
}
它並不理想,因為你實際上會用硬編碼字符串調用它(這通常是個壞主意)並且你將被迫只使用字符串,但它可以完成。 唯一的問題是它是否實用。
不幸的是, MessageFormat
API不支持命名參數,只支持參數索引:
模式及其解釋
MessageFormat使用以下格式的模式:
MessageFormatPattern:
String
MessageFormatPattern FormatElement String
FormatElement:
{ ArgumentIndex }
{ ArgumentIndex , FormatType }
{ ArgumentIndex , FormatType , FormatStyle }
有可能使用apache commons lang庫。
https://commons.apache.org/proper/commons-lang/
Properties messages = ...
Map<String, String> m = new HashMap<>();
m.put("name", "Mithu");
m.put("location", "Dhaka");
StrSubstitutor sub = new StrSubstitutor(m);
String msg = sub.replace(messages.getProperty("message.myMessage"));
// msg = This message is for Mithu in Dhaka
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.