MessageFormat
提供了一种以语言无关的方式生成串联消息的方法。使用它来构造显示给最终用户的消息。
MessageFormat
接受一组对象,对它们进行格式化,然后将格式化后的字符串插入到模式的适当位置。
注意:
MessageFormat
与其他Format
类的不同之处在于,您使用它的一个构造函数(而不是使用getInstance
风格的工厂方法)创建MessageFormat
对象。工厂方法不是必需的,因为MessageFormat
本身不实现特定于语言环境的行为。任何特定于语言环境的行为都由您提供的模式以及用于插入参数的子格式定义。
模式及其解释
MessageFormat
使用以下形式的模式:
MessageFormatPattern:
String
MessageFormatPattern FormatElement String
FormatElement:
{
ArgumentIndex }
{
ArgumentIndex , FormatType }
{
ArgumentIndex , FormatType , FormatStyle }
FormatType: one of
number date time choice
FormatStyle:
short
medium
long
full
integer
currency
percent
SubformatPattern
在String
中,一对单引号可以用来引用除单引号以外的任意字符。例如,模式字符串" '{0}'
" 代表字符串" {0}
“,而不是FormatElement
。在整个字符串中,单引号本身必须用双单引号 ' '
表示。例如,模式字符串 " '{' '}' "
被解释为'{
(引号开始和左花括号),"
(单引号)和}'
(右花括号和引号结束)的序列,而不是'{'
和'}'
(左、右花括号加引号): 表示字符串”{'}
“,而不是”{}
"
SubformatPattern
由其相应的子格式解释,并且应用子格式相关的模式规则。例如,模式字符串{1,number,$'#',##}
($'#',##
为SubformatPattern
)将生成一个带引号的数字格式,其结果如:“$#31,45
”。有关详细信息,请参阅每个Format子类文档。
任何不匹配的引号在给定模式的末尾被视为关闭。例如,模式字符串"'{0}
“被视为模式”'{0}'
"。
非引号模式中的任何花括号都必须是平衡的。例如,“ab {0} de
"和"ab '}' de
"是有效的模式,但"ab {0'}' de
”、“ab } de
"和”' '{' '
"不是。
ArgumentIndex
值是一个非负整数,使用数字’0’到’9’写入,并表示传入 format
方法的参数数组或parse
方法返回的结果数组的索引。
FormatType
和FormatStyle
值用于为Format
元素创建Format
实例。下表显示了这些值如何映射到Format
实例。未在表中显示的组合是非法的。SubformatPattern
必须是所使用的Format
子类的有效模式字符串。
用法
下面是一些用法示例。在真正的国际化程序中,消息格式模式和其他静态字符串当然是从资源包中获得的。其他参数将在运行时动态确定。
第一个示例使用静态方法MessageFormat.format
,它在内部创建一个一次性使用的MessageFormat
:
int planet = 7;
String event = "a disturbance in the Force";
String result = MessageFormat.format(
"At {1,time} on {1,date}, there was {2} on planet {0,number,integer}.",
planet, new Date(), event);
// At 10:27:05 on 2023-5-31, there was a disturbance in the Force on planet 7.