- java.lang.Object
-
- java.text.Format
-
- java.text.MessageFormat
-
- All Implemented Interfaces:
-
Serializable,Cloneable
public class MessageFormat extends Format
MessageFormat提供了一种以语言中立的方式产生级联消息的方法。 使用它来构建为最终用户显示的消息。MessageFormat采取一组对象,对它们进行格式化,然后将格式化的字符串插入到适当位置的模式中。注意:
MessageFormat与其他Format类别不同之处在于,您创建一个MessageFormat对象,其中一个构造函数(不是使用getInstance样式工厂方法)。 工厂方法不是必需的,因为MessageFormat本身不实现区域设置特定的行为。 任何特定于语言环境的行为都由您提供的模式以及用于插入参数的子格式定义。Patterns and Their Interpretation
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在字符串中 ,可以使用一对单引号来引用除单引号以外的任何字符。 例如,模式字符串
"'{0}'"表示字符串"{0}"而不是FormatElement 。 单引号本身必须用整个字符串中的双引号''表示。 例如,模式字符串"'{''}'"被解释为序列'{(起始引号和左大括号),''(单引号)和}'(右括号括号和引号结尾), 而不是'{'和'}'(引用左右大括号):代表字符串"{'}", 而不是"{}"。SubformatPattern由其对应的子格式解释,并且子格式依赖模式规则适用。 例如,模式字符串
"{1,number,$'#',##}"(SubformatPattern用下划线)会产生与井号的数字格式引述,具有结果如:"$#31,45"。 有关详细信息,请参阅每个Format子类文档。任何不匹配的报价在给定模式结束时被视为关闭。 例如,图案字符串
"'{0}"被视为图案"'{0}'"。任何不引用花样的花括号必须平衡。 例如,
"ab {0} de"和"ab '}' de"是有效的模式,但"ab {0'}' de","ab } de"和"''{''"都没有。- 警告:
-
不幸的是,消息格式模式中使用引号的规则显得有些混乱。
特别是,地方主义者并不总是明确单引号是否需要加倍。
确保通知本地化程序有关规则,并告知他们(例如,通过使用资源包源文件中的注释)
MessageFormat处理哪些字符串。 请注意,本地化程序可能需要在原始版本没有转换的字符串中使用单引号。
ArgumentIndex值是使用数字
'0'至'9'写入的非负整数,并表示传递给format方法的arguments数组的索引或由parse方法返回的结果数组。FormatType和FormatStyle值用于为format元素创建一个
Shows how FormatType and FormatStyle values map to Format instances FormatType FormatStyle Subformat Created (none) (none)Format实例。 下表显示了值映射到Format实例。 表中未显示的组合是非法的。 SubformatPattern必须是使用的Format子类的有效模式字符串。nullnumber(none)NumberFormat.getInstance(getLocale())integerNumberFormat.getIntegerInstance(getLocale())currencyNumberFormat.getCurrencyInstance(getLocale())percentNumberFormat.getPercentInstance(getLocale())SubformatPatternnewDecimalFormat(subformatPattern,DecimalFormatSymbols.getInstance(getLocale()))date(none)DateFormat.getDateInstance(DateFormat.DEFAULT, getLocale())shortDateFormat.getDateInstance(DateFormat.SHORT, getLocale())mediumDateFormat.getDateInstance(DateFormat.DEFAULT, getLocale())longDateFormat.getDateInstance(DateFormat.LONG, getLocale())fullDateFormat.getDateInstance(DateFormat.FULL, getLocale())SubformatPatternnewSimpleDateFormat(subformatPattern, getLocale())time(none)DateFormat.getTimeInstance(DateFormat.DEFAULT, getLocale())shortDateFormat.getTimeInstance(DateFormat.SHORT, getLocale())mediumDateFormat.getTimeInstance(DateFormat.DEFAULT, getLocale())longDateFormat.getTimeInstance(DateFormat.LONG, getLocale())fullDateFormat.getTimeInstance(DateFormat.FULL, getLocale())SubformatPatternnewSimpleDateFormat(subformatPattern, getLocale())choiceSubformatPatternnewChoiceFormat(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);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));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));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")}Synchronization
消息格式不同步。 建议为每个线程创建单独的格式实例。 如果多个线程同时访问格式,则必须在外部进行同步。
- 从以下版本开始:
- 1.1
- 另请参见:
-
Locale,Format,NumberFormat,DecimalFormat,DecimalFormatSymbols,ChoiceFormat,DateFormat,SimpleDateFormat, Serialized Form
-
-
Nested Class Summary
Nested Classes Modifier and Type Class 描述 static classMessageFormat.Field定义从MessageFormat.formatToCharacterIterator返回的AttributedCharacterIterator中用作属性键的MessageFormat.formatToCharacterIterator。
-
构造方法摘要
构造方法 Constructor 描述 MessageFormat(String pattern)为默认的FORMAT区域设置和指定的模式构造一个MessageFormat。MessageFormat(String pattern, Locale locale)为指定的区域设置和模式构造一个MessageFormat。
-
方法摘要
所有方法 静态方法 接口方法 具体的方法 Modifier and Type 方法 描述 voidapplyPattern(String pattern)设置此消息格式使用的模式。Objectclone()创建并返回此对象的副本。booleanequals(Object obj)两个消息格式对象之间的平等比较StringBufferformat(Object[] arguments, StringBuffer result, FieldPosition pos)格式化一个对象数组,并将MessageFormat的格式(格式化元素替换为格式化对象)StringBuffer到所提供的StringBuffer。StringBufferformat(Object arguments, StringBuffer result, FieldPosition pos)格式化一组对象,并将MessageFormat的格式(格式化元素替换为格式化对象)StringBuffer到所提供的StringBuffer。static Stringformat(String pattern, Object... arguments)使用给定的模式创建一个MessageFormat,并使用它来格式化给定的参数。AttributedCharacterIteratorformatToCharacterIterator(Object arguments)格式化一组对象,并将它们插入到MessageFormat的模式中,生成一个AttributedCharacterIterator。Format[]getFormats()获取用于先前设置的模式字符串中的格式元素的格式。Format[]getFormatsByArgumentIndex()获取用于传递到format方法中的值的格式或从parse方法返回的parse。LocalegetLocale()获取创建或比较子格式时使用的区域设置。inthashCode()生成消息格式对象的哈希码。Object[]parse(String source)从给定字符串的开头解析文本以产生一个对象数组。Object[]parse(String source, ParsePosition pos)解析字符串。ObjectparseObject(String source, ParsePosition pos)从字符串中解析文本以生成对象数组。voidsetFormat(int formatElementIndex, Format newFormat)设置在先前设置的模式字符串中使用具有给定格式元素索引的格式元素的格式。voidsetFormatByArgumentIndex(int argumentIndex, Format newFormat)设置使用给定参数索引的先前设置的模式字符串中的格式元素的格式。voidsetFormats(Format[] newFormats)设置用于先前设置的模式字符串中的格式元素的格式。voidsetFormatsByArgumentIndex(Format[] newFormats)设置用于传递给format方法或从parse方法返回的值的格式。voidsetLocale(Locale locale)设置创建或比较子格式时要使用的区域设置。StringtoPattern()返回表示消息格式的当前状态的模式。-
Methods inherited from class java.text.Format
format, parseObject
-
-
-
-
构造方法详细信息
-
MessageFormat
public MessageFormat(String pattern)
为默认的FORMAT区域设置和指定的模式构造一个MessageFormat。 构造函数首先设置区域设置,然后解析模式,并为其中包含的格式元素创建一个子格式列表。 模式及其解释在class description中规定。- 参数
-
pattern- 此消息格式的模式 - 异常
-
IllegalArgumentException- 如果模式无效 -
NullPointerException- 如果pattern是null
-
MessageFormat
public MessageFormat(String pattern, Locale locale)
为指定的区域设置和模式构造一个MessageFormat。 构造函数首先设置区域设置,然后解析模式,并为其中包含的格式元素创建一个子格式列表。 模式及其解释在class description中规定。- 参数
-
pattern- 此消息格式的模式 -
locale- 此消息格式的区域设置 - 异常
-
IllegalArgumentException- 如果模式无效 -
NullPointerException- 如果pattern是null - 从以下版本开始:
- 1.4
-
-
方法详细信息
-
setLocale
public void setLocale(Locale locale)
设置创建或比较子格式时要使用的区域设置。 这将影响后续呼叫- 到
applyPattern和toPattern方法,如果格式元素指定格式类型,因此具有在applyPattern方法中创建的子格式,以及 - 到
format和formatToCharacterIterator方法,如果格式元素不指定格式类型,因此在格式化方法中创建子格式。
- 参数
-
locale- 创建或比较子格式时要使用的区域设置
- 到
-
getLocale
public Locale getLocale()
获取创建或比较子格式时使用的区域设置。- 结果
- 创建或比较子格式时使用的区域设置
-
applyPattern
public void applyPattern(String pattern)
- 参数
-
pattern- 此消息格式的模式 - 异常
-
IllegalArgumentException- 如果模式无效 -
NullPointerException- 如果pattern是null
-
toPattern
public String toPattern()
返回表示消息格式的当前状态的模式。 该字符串由内部信息构成,因此不一定等于之前应用的模式。- 结果
- 表示消息格式的当前状态的模式
-
setFormatsByArgumentIndex
public void setFormatsByArgumentIndex(Format[] newFormats)
设置用于传递给format方法或从parse方法返回的值的格式。newFormats中元素的newFormats对应于在先前设置的模式字符串中使用的参数索引。 的格式中的顺序newFormats因此对应于在元素的顺序arguments阵列传递给format方法或由所述返回的结果阵列parse方法。如果一个参数索引用于模式字符串中的多个格式元素,则相应的新格式将用于所有这些格式元素。 如果模式字符串中的任何格式元素都不使用参数索引,则忽略相应的新格式。 如果提供的格式比所需的格式少,那么仅替换小于
newFormats.length参数索引的格式被替换。- 参数
-
newFormats- 要使用的新格式 - 异常
-
NullPointerException- 如果newFormats为空 - 从以下版本开始:
- 1.4
-
setFormats
public void setFormats(Format[] newFormats)
设置用于先前设置的模式字符串中的格式元素的格式。newFormats中格式的newFormats对应于模式字符串中的格式元素的顺序。如果模式字符串所需的格式多于其他格式,则忽略其余格式。 如果提供的格式少于所需的格式,则仅替换第一个
newFormats.length格式。由于模式字符串中的格式元素的顺序通常在本地化期间发生变化,因此通常最好使用
setFormatsByArgumentIndex方法,该方法假定与arguments数组中的元素的顺序相对应的格式顺序传递给format方法或结果数组由parse方法归还。- 参数
-
newFormats- 要使用的新格式 - 异常
-
NullPointerException- 如果newFormats为空
-
setFormatByArgumentIndex
public void setFormatByArgumentIndex(int argumentIndex, Format newFormat)设置使用给定参数索引的先前设置的模式字符串中的格式元素的格式。 参数索引是格式元素定义的一部分,并且表示传递给format方法的arguments数组的索引或由parse方法返回的结果数组。如果参数索引用于模式字符串中的多个格式元素,则新格式将用于所有此类格式元素。 如果参数索引不用于模式字符串中的任何格式元素,则将忽略新格式。
- 参数
-
argumentIndex- 要使用新格式的参数索引 -
newFormat- 使用的新格式 - 从以下版本开始:
- 1.4
-
setFormat
public void setFormat(int formatElementIndex, Format newFormat)设置在先前设置的模式字符串中使用具有给定格式元素索引的格式元素的格式。 格式元素索引是从模式字符串开始计数的格式元素的从零开始的数字。由于模式字符串中的格式元素的顺序通常在本地化期间发生变化,所以通常最好使用
setFormatByArgumentIndex方法,该方法根据它们指定的参数索引来访问格式元素。- 参数
-
formatElementIndex- 模式中格式元素的索引 -
newFormat- 用于指定格式元素的格式 - 异常
-
ArrayIndexOutOfBoundsException- 如果formatElementIndex等于或大于模式字符串中格式元素的数量
-
getFormatsByArgumentIndex
public Format[] getFormatsByArgumentIndex()
获取用于传递给format方法的值或从parse方法返回的parse。 返回数组中元素的索引对应于先前设置的模式字符串中使用的参数索引。 的返回的数组中的格式的顺序因此对应于在元素的顺序arguments阵列传递给format方法或由所述返回的结果阵列parse方法。如果模式字符串中的多个格式元素使用参数索引,则在数组中返回用于最后一个格式元素的格式。 如果模式字符串中的任何格式元素都不使用参数索引,则在数组中返回null。
- 结果
- 用于模式中参数的格式
- 从以下版本开始:
- 1.4
-
getFormats
public Format[] getFormats()
获取用于先前设置的模式字符串中的格式元素的格式。 返回数组中格式的顺序对应于模式字符串中格式元素的顺序。由于模式字符串中的格式元素的顺序通常在本地化期间发生变化,所以通常最好使用
getFormatsByArgumentIndex方法,该方法假定与arguments数组中的元素的顺序相对应的格式顺序传递给format方法或返回的结果数组通过parse方法。- 结果
- 用于格式元素格式的格式
-
format
public final StringBuffer format(Object[] arguments, StringBuffer result, FieldPosition pos)
格式化一个对象数组,并将MessageFormat的格式附加到格式化对象的格式元素到所提供的StringBuffer。代替各个格式元素的文本是从格式元素的当前子格式和格式元素参数索引处的
Examples of subformat,argument,and formatted text Subformat Argument Formatted Text any unavailablearguments元素派生的,如下表第一个匹配行所示。 如果arguments为null或少于argumentIndex + 1元素,则参数不可用 。"{" + argumentIndex + "}"anynull"null"instanceof ChoiceFormatanysubformat.format(argument).indexOf('{') >= 0 ?
(new MessageFormat(subformat.format(argument), getLocale())).format(argument) : subformat.format(argument)!= nullanysubformat.format(argument)nullinstanceof NumberNumberFormat.getInstance(getLocale()).format(argument)nullinstanceof DateDateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, getLocale()).format(argument)nullinstanceof Stringargumentnullanyargument.toString()如果
pos为非空,并且参考Field.ARGUMENT,将返回第一个格式化字符串的位置。- 参数
-
arguments- 要格式化和替换的对象数组。 -
result- 附加文本。 -
pos- 输入:如果需要,对齐字段。 输出:对齐字段的偏移量。 - 结果
-
字符串缓冲区作为
result,附带格式化的文本 - 异常
-
IllegalArgumentException- 如果arguments数组中的参数不是使用它的格式元素所期望的类型。 -
NullPointerException- 如果result是null
-
format
public static String format(String pattern, Object... arguments)
使用给定的模式创建一个MessageFormat,并使用它来格式化给定的参数。 这相当于(newMessageFormat(pattern)).format(arguments, new StringBuffer(), null).toString()- 参数
-
pattern- 模式字符串 -
arguments- 要格式化的对象 - 结果
- 格式化的字符串
- 异常
-
IllegalArgumentException- 如果模式无效,或者arguments数组中的参数不是使用格式化元素所期望的类型。 -
NullPointerException- 如果pattern是null
-
format
public final StringBuffer format(Object arguments, StringBuffer result, FieldPosition pos)
格式化一组对象,并将MessageFormat的格式附加到已提供的StringBuffer的格式化对象的格式元素中。 这相当于format((Object[]) arguments, result, pos)- Specified by:
-
format在Format - 参数
-
arguments- 要格式化和替换的对象数组。 -
result- 附加文本。 -
pos- 输入:如果需要,对齐字段。 输出:对齐字段的偏移量。 - 结果
-
字符串缓冲区作为
toAppendTo,附带格式化的文本 - 异常
-
IllegalArgumentException- 如果arguments数组中的参数不是使用它的格式元素所期望的类型。 -
NullPointerException- 如果result是null
-
formatToCharacterIterator
public AttributedCharacterIterator formatToCharacterIterator(Object arguments)
格式化一组对象并将其插入到MessageFormat的模式中,产生一个AttributedCharacterIterator。 您可以使用返回的AttributedCharacterIterator构建生成的字符串,以及确定有关生成的字符串的信息。返回的
AttributedCharacterIterator的文本与返回的文本相同format(arguments, new StringBuffer(), null).toString()此外,
AttributedCharacterIterator至少包含属性,指示从arguments数组中的参数生成文本的arguments。 这些属性的键的类型为MessageFormat.Field,它们的值为Integer对象,指示生成文本的参数的arguments数组中的索引。从底层的属性/值
Format实例即MessageFormat用途也将被放置在所得AttributedCharacterIterator。 这样,您不仅可以在生成的字符串中找到参数的位置,还可以找到它所包含的字段。- 重写:
-
formatToCharacterIterator在Format - 参数
-
arguments- 要格式化和替换的对象数组。 - 结果
- AttributedCharacterIterator描述格式化的值。
- 异常
-
NullPointerException- 如果arguments为空。 -
IllegalArgumentException- 如果arguments数组中的参数不是使用它的格式元素所期望的类型。 - 从以下版本开始:
- 1.4
-
parse
public Object[] parse(String source, ParsePosition pos)
解析字符串。警告:在许多情况下,解析可能会失败。 例如:
- 如果其中一个参数不发生在模式中。
- 如果参数的格式丢失信息,例如使用大量格式化为“许多”的选择格式。
- 还没有处理递归(其中替换的字符串包含{n}个引用)。
- 如果解析的某些部分含糊不清,则不会总是找到匹配(或正确的匹配)。 例如,如果模式“{1},{2}”与字符串参数{“a,b”,“c”}一起使用,则它将格式化为“a,b,c”。 当结果被解析时,它将返回{“a”,“b,c”}。
- 如果单个参数在字符串中被多次解析,则后来的解析获胜。
- 参数
-
source- 要解析的字符串 -
pos- 解析位置 - 结果
- 一组解析的对象
- 异常
-
NullPointerException- 如果pos是null为非空source字符串。
-
parse
public Object[] parse(String source) throws ParseException
- 参数
-
source- AString其开头应该被解析。 - 结果
-
从字符串中解析出一个
Object数组。 - 异常
-
ParseException- 如果无法解析指定字符串的开头。
-
parseObject
public Object parseObject(String source, ParsePosition pos)
从字符串中解析文本以生成对象数组。该方法尝试从
pos给出的索引开始解析文本。 如果解析成功,则pos的索引将更新为使用最后一个字符后的索引(解析不一定使用字符串末尾的所有字符),并返回已解析的对象数组。 更新的pos可用于指示下一次调用此方法的起始点。 如果发生错误,则pos的索引未更改,错误索引pos设置为发生错误的字符的索引,返回null。有关消息解析的更多信息,请参阅
parse(String, ParsePosition)方法。- Specified by:
-
parseObject在Format - 参数
-
source- AString,其中一部分应该被解析。 -
pos- 具有ParsePosition索引和错误索引信息的ParsePosition对象。 - 结果
-
从字符串中解析一个
Object数组。 万一出错,返回null。 - 异常
-
NullPointerException- 如果pos为空。
-
equals
public boolean equals(Object obj)
两个消息格式对象之间的平等比较- 重写:
-
equals在Object - 参数
-
obj- 与之比较的参考对象。 - 结果
-
true如果此对象与obj参数相同;false否则。 - 另请参见:
-
Object.hashCode(),HashMap
-
hashCode
public int hashCode()
生成消息格式对象的哈希码。- 重写:
-
hashCode在Object - 结果
- 该对象的哈希码值。
- 另请参见:
-
Object.equals(java.lang.Object),System.identityHashCode(java.lang.Object)
-
-