public class MessageFormat
extends Format
| java.lang.Object | ||
| java.text.Format | ||
| java.text.MessageFormat | ||
MessageFormat提供了一种以与语言MessageFormat的方式生成连接消息的方法。 使用它来构造显示给最终用户的消息。
MessageFormat需要一组对象,对它们进行格式化,然后将格式化的字符串插入到适当位置的模式中。
注意: MessageFormat与其他Format类不同之处在于,您使用其构造函数之一(而不是getInstance样式工厂方法)创建了MessageFormat对象。 工厂方法不是必需的,因为MessageFormat本身并不实现特定于语言环境的行为。 任何特定于语言环境的行为都由您提供的模式以及用于插入参数的子格式定义。
MessageFormat uses patterns of the following form:
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
在一个字符串中 ,可以使用一对单引号引用除单引号以外的任意字符。 例如,模式字符串"'{0}'"表示字符串"{0}" ,而不是FormatElement 。 单个报价本身必须在整个字符串中用加倍的单引号''表示。 例如,模式字符串"'{''}'"被解释为'{ (引号开头和左大括号), '' (单引号)和}' (右引号和}'结尾)的'{' , 而不是 '{'和'}' (引用的引号左右花括号):代表字符串"{'}" , 而不是 "{}" 。
一个SubformatPattern由其相应的子格式解释,并且应用了依赖于子格式的模式规则。 例如,模式字符串"{1,number,$'#',##}" (具有下划线的SubformatPattern )将生成带引号的磅符号的数字格式,其结果如下: "$#31,45" 。 有关详细信息,请参阅每个Format子类文档。
任何不匹配的引用在给定模式结束时被视为关闭。 例如,模式字符串"'{0}"被视为模式"'{0}'" 。
任何未加引号的模式中的花括号必须平衡。 例如, "ab {0} de"和"ab '}' de"是有效的模式,但"ab {0'}' de" , "ab } de"和"''{''"都没有。
MessageFormat. Note that localizers may need to use single quotes in translated strings where the original version doesn't have them.
ArgumentIndex值是一个使用数字 '0'到 '9'编写的非负整数,并且表示传递给 format方法的 arguments数组或 format方法返回的结果数组的 parse 。
FormatType和FormatStyle值用于为format元素创建一个Format实例。 下表显示了这些值如何映射到Format实例。 表中未显示的组合是非法的。 SubformatPattern必须是所使用的Format子类的有效模式字符串。
| FormatType | FormatStyle | Subformat Created |
|---|---|---|
| (none) | (none) | null |
number |
(none) | NumberFormat.getInstance(getLocale()) |
integer |
NumberFormat.getIntegerInstance(getLocale()) |
|
currency |
NumberFormat.getCurrencyInstance(getLocale()) |
|
percent |
NumberFormat.getPercentInstance(getLocale()) |
|
| SubformatPattern | new DecimalFormat(subformatPattern, DecimalFormatSymbols.getInstance(getLocale())) |
|
date |
(none) | DateFormat.getDateInstance(DEFAULT, getLocale()) |
short |
DateFormat.getDateInstance(SHORT, getLocale()) |
|
medium |
DateFormat.getDateInstance(DEFAULT, getLocale()) |
|
long |
DateFormat.getDateInstance(LONG, getLocale()) |
|
full |
DateFormat.getDateInstance(FULL, getLocale()) |
|
| SubformatPattern | new SimpleDateFormat(subformatPattern, getLocale()) |
|
time |
(none) | DateFormat.getTimeInstance(DEFAULT, getLocale()) |
short |
DateFormat.getTimeInstance(SHORT, getLocale()) |
|
medium |
DateFormat.getTimeInstance(DEFAULT, getLocale()) |
|
long |
DateFormat.getTimeInstance(LONG, getLocale()) |
|
full |
DateFormat.getTimeInstance(FULL, getLocale()) |
|
| SubformatPattern | new SimpleDateFormat(subformatPattern, getLocale()) |
|
choice |
SubformatPattern | new ChoiceFormat(subformatPattern) |
以下是一些使用示例。 在真正的国际化程序中,消息格式模式和其他静态字符串当然会从资源包中获得。 其他参数将在运行时动态确定。
第一个示例使用静态方法 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);
The output is:
At 12:30 PM on Jul 3, 2053, there was a disturbance in the Force on planet 7.
以下示例创建可以重复使用的 MessageFormat实例:
int fileCount = 1273;
String diskName = "MyDisk";
Object[] testArgs = {new Long(fileCount), diskName};
MessageFormat form = new MessageFormat(
"The disk \"{1}\" contains {0} file(s).");
System.out.println(form.format(testArgs));
The output with different values for
fileCount:
The disk "MyDisk" contains 0 file(s). The disk "MyDisk" contains 1 file(s). The disk "MyDisk" contains 1,273 file(s).
对于更复杂的模式,您可以使用 ChoiceFormat生成单数和复数的正确形式:
MessageFormat form = new MessageFormat("The disk \"{1}\" contains {0}.");
double[] filelimits = {0,1,2};
String[] filepart = {"no files","one file","{0,number} files"};
ChoiceFormat fileform = new ChoiceFormat(filelimits, filepart);
form.setFormatByArgumentIndex(0, fileform);
int fileCount = 1273;
String diskName = "MyDisk";
Object[] testArgs = {new Long(fileCount), diskName};
System.out.println(form.format(testArgs));
The output with different values for
fileCount:
The disk "MyDisk" contains no files. The disk "MyDisk" contains one file. The disk "MyDisk" contains 1,273 files.
您可以以编程方式创建ChoiceFormat ,如上例所示,或使用模式。 有关更多信息,请参阅ChoiceFormat 。
form.applyPattern(
"There {0,choice,0#are no files|1#is one file|1<are {0,number,integer} files}.");
注意:如上所述,由ChoiceFormat中的MessageFormat生成的字符串被视为特殊MessageFormat ; “{”的出现被用于指示子格式,并导致递归。 如果以编程方式创建MessageFormat和ChoiceFormat (而不是使用字符串模式),请注意不要产生自身递归的格式,这将导致无限循环。
当一个参数在字符串中被多次解析时,最后的匹配将是解析的最终结果。 例如,
MessageFormat mf = new MessageFormat("{0,number,#.##}, {0,number,#.#}");
Object[] objs = {new Double(3.1415)};
String result = mf.format( objs );
// result now equals "3.14, 3.1"
objs = null;
objs = mf.parse(result, new ParsePosition(0));
// objs now equals {new Double(3.1)}
同样,使用包含多次出现相同参数的模式解析对象MessageFormat将返回最后一次匹配。 例如,
MessageFormat mf = new MessageFormat("{0}, {0}, {0}");
String forParsing = "x, y, z";
Object[] objs = mf.parse(forParsing, new ParsePosition(0));
// result now equals {new String("z")}
消息格式不同步。 建议为每个线程创建单独的格式实例。 如果多个线程同时访问一个格式,它必须在外部同步。
也可以看看:
Nested classes |
|
|---|---|
class |
MessageFormat.Field 定义从 |
Public constructors |
|
|---|---|
MessageFormat(String pattern) 构造默认语言环境和指定模式的MessageFormat。 |
|
MessageFormat(String pattern, Locale locale) 为指定的语言环境和模式构造MessageFormat。 |
|
公共方法(Public methods) |
|
|---|---|
void |
applyPattern(String pattern) 设置此消息格式使用的模式。 |
Object |
clone() 创建并返回此对象的副本。 |
boolean |
equals(Object obj) 两个消息格式对象之间的平等比较 |
final StringBuffer |
format(Object[] arguments, StringBuffer result, FieldPosition pos) 格式化对象数组,并将 |
final StringBuffer |
format(Object arguments, StringBuffer result, FieldPosition pos) 格式化对象数组并将 |
static String |
format(String pattern, Object... arguments) 用给定的模式创建一个MessageFormat并使用它来格式化给定的参数。 |
AttributedCharacterIterator |
formatToCharacterIterator(Object arguments) 格式化一组对象并将它们插入到 |
Format[] |
getFormats() 获取用于先前设置的模式字符串中格式元素的格式。 |
Format[] |
getFormatsByArgumentIndex() 获取用于传递给 |
Locale |
getLocale() 获取创建或比较子格式时使用的语言环境。 |
int |
hashCode() 为消息格式对象生成哈希码。 |
Object[] |
parse(String source) 从给定字符串的开头分析文本以生成对象数组。 |
Object[] |
parse(String source, ParsePosition pos) 分析字符串。 |
Object |
parseObject(String source, ParsePosition pos) 分析字符串中的文本以生成对象数组。 |
void |
setFormat(int formatElementIndex, Format newFormat) 在先前设置的模式字符串中设置格式元素使用的格式,格式元素具有给定的格式元素索引。 |
void |
setFormatByArgumentIndex(int argumentIndex, Format newFormat) 设置用于先前设置的模式字符串中使用给定参数索引的格式元素的格式。 |
void |
setFormats(Format[] newFormats) 设置用于先前设置的模式字符串中格式元素的格式。 |
void |
setFormatsByArgumentIndex(Format[] newFormats) 设置用于传递给 |
void |
setLocale(Locale locale) 设置创建或比较子格式时要使用的语言环境。 |
String |
toPattern() 返回表示消息格式当前状态的模式。 |
继承方法(Inherited methods) |
|
|---|---|
java.text.Format
|
|
java.lang.Object
|
|
MessageFormat (String pattern)
构造默认语言环境和指定模式的MessageFormat。 构造函数首先设置区域设置,然后解析模式并为其中包含的格式元素创建子格式列表。 模式及其解释在class description中指定。
| 参数(Parameters) | |
|---|---|
pattern |
String: the pattern for this message format |
| 抛出异常(Throws) | |
|---|---|
IllegalArgumentException |
if the pattern is invalid |
MessageFormat (String pattern, Locale locale)
为指定的语言环境和模式构造MessageFormat。 构造函数首先设置区域设置,然后解析模式并为其中包含的格式元素创建子格式列表。 模式及其解释在class description中指定。
| 参数(Parameters) | |
|---|---|
pattern |
String: the pattern for this message format |
locale |
Locale: the locale for this message format |
| 抛出异常(Throws) | |
|---|---|
IllegalArgumentException |
if the pattern is invalid |
void applyPattern (String pattern)
设置此消息格式使用的模式。 该方法解析模式并为其中包含的格式元素创建一个子格式列表。 模式及其解释在class description中指定。
| 参数(Parameters) | |
|---|---|
pattern |
String: the pattern for this message format |
| 抛出异常(Throws) | |
|---|---|
IllegalArgumentException |
if the pattern is invalid |
Object clone ()
创建并返回此对象的副本。
| 返回(Returns) | |
|---|---|
Object |
a clone of this instance. |
boolean equals (Object obj)
两个消息格式对象之间的平等比较
| 参数(Parameters) | |
|---|---|
obj |
Object: the reference object with which to compare. |
| 返回(Returns) | |
|---|---|
boolean |
true if this object is the same as the obj argument; false otherwise. |
StringBuffer format (Object[] arguments, StringBuffer result, FieldPosition pos)
格式化一个对象数组,并将 MessageFormat的模式(格式化元素替换为格式化对象) StringBuffer到提供的 StringBuffer 。
用于各个格式元素取代的文本被从格式元件的电流子格式和派生arguments元件格式元素的参数索引在由下表的第一匹配线所示。 如果arguments是null或者少于argumentIndex + 1元素,则参数不可用 。
| Subformat | Argument | Formatted Text |
|---|---|---|
| any | unavailable | "{" + argumentIndex + "}" |
| any | null |
"null" |
instanceof ChoiceFormat |
any | subformat.format(argument).indexOf('{') >= 0 ? |
!= null |
any | subformat.format(argument) |
null |
instanceof Number |
NumberFormat.getInstance(getLocale()).format(argument) |
null |
instanceof Date |
DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, getLocale()).format(argument) |
null |
instanceof String |
argument |
null |
any | argument.toString() |
如果 pos非空,并且指向 Field.ARGUMENT ,则返回第一个格式化字符串的位置。
| 参数(Parameters) | |
|---|---|
arguments |
Object: an array of objects to be formatted and substituted. |
result |
StringBuffer: where text is appended. |
pos |
FieldPosition: On input: an alignment field, if desired. On output: the offsets of the alignment field. |
| 返回(Returns) | |
|---|---|
StringBuffer |
|
| 抛出异常(Throws) | |
|---|---|
IllegalArgumentException |
if an argument in the arguments array is not of the type expected by the format element(s) that use it. |
StringBuffer format (Object arguments, StringBuffer result, FieldPosition pos)
格式化对象数组,并将MessageFormat的模式(格式化元素替换为格式化对象) StringBuffer到提供的StringBuffer 。 这相当于
format((Object[]) arguments, result, pos)
| 参数(Parameters) | |
|---|---|
arguments |
Object: an array of objects to be formatted and substituted. |
result |
StringBuffer: where text is appended. |
pos |
FieldPosition: On input: an alignment field, if desired. On output: the offsets of the alignment field. |
| 返回(Returns) | |
|---|---|
StringBuffer |
the string buffer passed in as toAppendTo, with formatted text appended |
| 抛出异常(Throws) | |
|---|---|
IllegalArgumentException |
if an argument in the arguments array is not of the type expected by the format element(s) that use it. |
String format (String pattern, Object... arguments)
用给定的模式创建一个MessageFormat并使用它来格式化给定的参数。 这相当于
(new MessageFormat(pattern)).format(arguments, new StringBuffer(), null).toString()
| 参数(Parameters) | |
|---|---|
pattern |
String
|
arguments |
Object
|
| 返回(Returns) | |
|---|---|
String |
|
| 抛出异常(Throws) | |
|---|---|
IllegalArgumentException |
if the pattern is invalid, or if an argument in the arguments array is not of the type expected by the format element(s) that use it. |
AttributedCharacterIterator formatToCharacterIterator (Object arguments)
格式化一组对象并将它们插入到MessageFormat的模式中,产生一个AttributedCharacterIterator 。 您可以使用返回的AttributedCharacterIterator来生成结果字符串,以及确定有关生成的字符串的信息。
返回的 AttributedCharacterIterator的文本与将返回的文本相同
format(arguments, new StringBuffer(), null).toString()
另外, AttributedCharacterIterator至少包含指示arguments数组中的参数生成文本的属性。 这些属性的键类型为MessageFormat.Field ,它们的值为Integer对象,指示生成文本的参数的arguments数组中的索引。
来自MessageFormat使用的底层Format实例的属性/值也将被放置在结果AttributedCharacterIterator 。 这使您不仅可以找到参数在结果字符串中的位置,而且还可以找到它包含的字段。
| 参数(Parameters) | |
|---|---|
arguments |
Object: an array of objects to be formatted and substituted. |
| 返回(Returns) | |
|---|---|
AttributedCharacterIterator |
AttributedCharacterIterator describing the formatted value. |
| 抛出异常(Throws) | |
|---|---|
NullPointerException |
if arguments is null. |
IllegalArgumentException |
if an argument in the arguments array is not of the type expected by the format element(s) that use it. |
Format[] getFormats ()
获取用于先前设置的模式字符串中格式元素的格式。 返回数组中格式的顺序对应于模式字符串中格式元素的顺序。
由于模式字符串中格式元素的顺序在本地化过程中经常发生变化,因此使用 getFormatsByArgumentIndex方法通常会更好,该方法假定格式顺序与 arguments数组中传递给 format方法或返回结果数组的元素顺序相对应由 parse方法。
| 返回(Returns) | |
|---|---|
Format[] |
the formats used for the format elements in the pattern |
Format[] getFormatsByArgumentIndex ()
获取用于传递给format方法的值或从parse方法返回的值的格式。 返回数组中元素的索引与先前设置的模式字符串中使用的参数索引相对应。 返回数组中格式的顺序因此对应于传递给format方法的arguments数组中元素的顺序或format方法返回的结果数组的parse 。
如果参数索引用于模式字符串中的多个格式元素,则用于最后一个这样的格式元素的格式将返回到数组中。 如果参数索引不用于模式字符串中的任何格式元素,则返回数组中的null。
| 返回(Returns) | |
|---|---|
Format[] |
the formats used for the arguments within the pattern |
Locale getLocale ()
获取创建或比较子格式时使用的语言环境。
| 返回(Returns) | |
|---|---|
Locale |
the locale used when creating or comparing subformats |
int hashCode ()
为消息格式对象生成哈希码。
| 返回(Returns) | |
|---|---|
int |
a hash code value for this object. |
Object[] parse (String source)
从给定字符串的开头分析文本以生成对象数组。 该方法可能不会使用给定字符串的整个文本。
有关消息解析的更多信息,请参阅 parse(String, ParsePosition)方法。
| 参数(Parameters) | |
|---|---|
source |
String: A String whose beginning should be parsed. |
| 返回(Returns) | |
|---|---|
Object[] |
An Object array parsed from the string. |
| 抛出异常(Throws) | |
|---|---|
ParseException |
if the beginning of the specified string cannot be parsed. |
Object[] parse (String source, ParsePosition pos)
分析字符串。
注意事项:在许多情况下,解析可能会失败。 例如:
| 参数(Parameters) | |
|---|---|
source |
String
|
pos |
ParsePosition
|
| 返回(Returns) | |
|---|---|
Object[] |
|
Object parseObject (String source, ParsePosition pos)
分析字符串中的文本以生成对象数组。
该方法尝试解析从pos给出的索引处开始的文本。 如果解析成功,则在使用最后一个字符(解析不一定使用到字符串末尾的所有字符)之后,将索引pos更新为索引,并返回解析的对象数组。 更新的pos可用于指示下一次调用此方法的起点。 如果发生错误,那么索引pos不会更改,错误索引pos将设置为发生错误的字符的索引,并返回null。
有关消息解析的更多信息,请参阅 parse(String, ParsePosition)方法。
| 参数(Parameters) | |
|---|---|
source |
String: A String, part of which should be parsed. |
pos |
ParsePosition: A ParsePosition object with index and error index information as described above. |
| 返回(Returns) | |
|---|---|
Object |
An Object array parsed from the string. In case of error, returns null. |
| 抛出异常(Throws) | |
|---|---|
NullPointerException |
if pos is null. |
void setFormat (int formatElementIndex,
Format newFormat)
在先前设置的模式字符串中设置格式元素使用的格式,格式元素具有给定的格式元素索引。 格式元素索引是从模式字符串开始计数的格式元素的从零开始的数字。
由于模式字符串中格式元素的顺序在本地化过程中经常发生变化,因此通常使用 setFormatByArgumentIndex方法更好,该方法根据它们指定的参数索引访问格式元素。
| 参数(Parameters) | |
|---|---|
formatElementIndex |
int: the index of a format element within the pattern |
newFormat |
Format: the format to use for the specified format element |
| 抛出异常(Throws) | |
|---|---|
ArrayIndexOutOfBoundsException |
if formatElementIndex is equal to or larger than the number of format elements in the pattern string |
void setFormatByArgumentIndex (int argumentIndex,
Format newFormat)
设置用于先前设置的模式字符串中使用给定参数索引的格式元素的格式。 参数索引是格式元素定义的一部分,表示传递给format方法的arguments数组或由parse方法返回的结果数组的parse 。
如果参数索引用于模式字符串中的多个格式元素,则新格式将用于所有此类格式元素。 如果参数索引不用于模式字符串中的任何格式元素,则新格式将被忽略。
| 参数(Parameters) | |
|---|---|
argumentIndex |
int: the argument index for which to use the new format |
newFormat |
Format: the new format to use |
void setFormats (Format[] newFormats)
设置用于先前设置的模式字符串中格式元素的格式。 格式在newFormats中的顺序对应于模式字符串中格式元素的顺序。
如果提供了比模式字符串所需格式更多的格式,则其余格式将被忽略。 如果提供的格式少于需要的格式,则只替换第一个newFormats.length格式。
由于模式字符串中格式元素的顺序在本地化过程中经常发生变化,因此使用 setFormatsByArgumentIndex方法通常会更好,该方法假定格式顺序与 arguments数组中元素的顺序相对应, arguments传递给 format方法或结果数组由 parse方法返回。
| 参数(Parameters) | |
|---|---|
newFormats |
Format: the new formats to use |
| 抛出异常(Throws) | |
|---|---|
NullPointerException |
if newFormats is null |
void setFormatsByArgumentIndex (Format[] newFormats)
设置用于传递给format方法的值或从parse方法返回的值的格式。 newFormats中元素的newFormats对应于先前设置的模式字符串中使用的参数索引。 newFormats中格式的newFormats因此对应于传递给format方法的arguments数组中元素的顺序或format方法返回的结果数组的parse 。
如果参数索引用于模式字符串中的多个格式元素,则相应的新格式将用于所有此类格式元素。 如果参数索引不用于模式字符串中的任何格式元素,则忽略相应的新格式。 如果提供的格式少于需要的格式, newFormats.length替换参数索引小于newFormats.length的格式。
| 参数(Parameters) | |
|---|---|
newFormats |
Format: the new formats to use |
| 抛出异常(Throws) | |
|---|---|
NullPointerException |
if newFormats is null |
void setLocale (Locale locale)
设置创建或比较子格式时要使用的语言环境。 这会影响后续调用
applyPattern and toPattern methods if format elements specify a format type and therefore have the subformats created in the applyPattern method, as well as format and formatToCharacterIterator methods if format elements do not specify a format type and therefore have the subformats created in the formatting methods. | 参数(Parameters) | |
|---|---|
locale |
Locale: the locale to be used when creating or comparing subformats |
String toPattern ()
返回表示消息格式当前状态的模式。 该字符串由内部信息构成,因此不一定等于先前应用的模式。
| 返回(Returns) | |
|---|---|
String |
a pattern representing the current state of the message format |