Spec-Zone .ru
спецификации, руководства, описания, API
JavaTM 2 Platform
Standard Edition

java.text
Class MessageFormat

java.lang.Object
  |
  +--java.text.Format
        |
        +--java.text.MessageFormat

public class MessageFormat
extends Format

MessageFormat provides a means to produce concatenated messages in language-neutral way. Use this to construct messages displayed for end users.

MessageFormat takes a set of objects, formats them, then inserts the formatted strings into the pattern at the appropriate places.

Note: MessageFormat differs from the other Format classes in that you create a MessageFormat object with one of its constructors (not with a getInstance style factory method). The factory methods aren't necessary because MessageFormat doesn't require any complex setup for a given locale. In fact, MessageFormat doesn't implement any locale specific behavior at all. It just needs to be set up on a sentence by sentence basis.

Here are some examples of usage:

 Object[] arguments = {
     new Integer(7),
     new Date(System.currentTimeMillis()),
     "a disturbance in the Force"
 };

 String result = MessageFormat.format(
     "At {1,time} on {1,date}, there was {2} on planet {0,number,integer}.",
     arguments);

 output: At 12:30 PM on Jul 3, 2053, there was a disturbance
           in the Force on planet 7.

 
Typically, the message format will come from resources, and the arguments will be dynamically set at runtime.

Example 2:

 Object[] testArgs = {new Long(3), "MyDisk"};

 MessageFormat form = new MessageFormat(
     "The disk \"{1}\" contains {0} file(s).");

 System.out.println(form.format(testArgs));

 // output, with different testArgs
 output: The disk "MyDisk" contains 0 file(s).
 output: The disk "MyDisk" contains 1 file(s).
 output: The disk "MyDisk" contains 1,273 file(s).
 

The pattern is of the form:

 messageFormatPattern := string ( "{" messageFormatElement "}" string )*

 messageFormatElement := argument { "," elementFormat }

 elementFormat := "time" { "," datetimeStyle }
                | "date" { "," datetimeStyle }
                | "number" { "," numberStyle }
                | "choice" { "," choiceStyle }

 datetimeStyle := "short"
                  | "medium"
                  | "long"
                  | "full"
                  | dateFormatPattern

 numberStyle := "currency"
               | "percent"
               | "integer"
               | numberFormatPattern

 choiceStyle := choiceFormatPattern
 
If there is no elementFormat, then the argument must be a string, which is substituted. If there is no dateTimeStyle or numberStyle, then the default format is used (for example, NumberFormat.getInstance, DateFormat.getTimeInstance, or DateFormat.getInstance).

In strings, single quotes can be used to quote the "{" (curly brace) if necessary. A real single quote is represented by ''. Inside a messageFormatElement, quotes are not removed. For example, {1,number,$'#',##} will produce a number format with the pound-sign quoted, with a result such as: "$#31,45".

If a pattern is used, then unquoted braces in the pattern, if any, must match: that is, "ab {0} de" and "ab '}' de" are ok, but "ab {0'}' de" and "ab } de" are not.

The argument is a number from 0 to 9, which corresponds to the arguments presented in an array to be formatted.

It is ok to have unused arguments in the array. With missing arguments or arguments that are not of the right class for the specified format, a ParseException is thrown. First, format checks to see if a Format object has been specified for the argument with the setFormats method. If so, then format uses that Format object to format the argument. Otherwise, the argument is formatted based on the object's type. If the argument is a Number, then format uses NumberFormat.getInstance to format the argument; if the argument is a Date, then format uses DateFormat.getDateTimeInstance to format the argument. Otherwise, it uses the toString method.

For more sophisticated patterns, you can use a ChoiceFormat to get output such as:

 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.setFormat(1,fileform); // NOT zero, see below

 Object[] testArgs = {new Long(12373), "MyDisk"};

 System.out.println(form.format(testArgs));

 // output, with different testArgs
 output: The disk "MyDisk" contains no files.
 output: The disk "MyDisk" contains one file.
 output: The disk "MyDisk" contains 1,273 files.
 
You can either do this programmatically, as in the above example, or by using a pattern (see ChoiceFormat for more information) as in:
 form.applyPattern(
    "There {0,choice,0#are no files|1#is one file|1#are {0,number,integer} files}.");
 

Note: As we see above, the string produced by a ChoiceFormat in MessageFormat is treated specially; occurances of '{' are used to indicated subformats, and cause recursion. If you create both a MessageFormat and ChoiceFormat programmatically (instead of using the string patterns), then be careful not to produce a format that recurses on itself, which will cause an infinite loop.

Note: formats are numbered by order of variable in the string. This is not the same as the argument numbering! For example: with "abc{2}def{3}ghi{0}...",

When a single argument is parsed more than once in the string, the last match will be the final result of the parsing. For example,

 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)}
 

Likewise, parsing with a MessageFormat object using patterns containing multiple occurances of the same argument would return the last match. For example,

 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")}
 

You can use setLocale followed by applyPattern (and then possibly setFormat) to re-initialize a MessageFormat with a different locale.

See Also:
Locale, Format, NumberFormat, DecimalFormat, ChoiceFormat, Serialized Form

Constructor Summary
MessageFormat(String pattern)
          Constructs with the specified pattern.
 
Method Summary
 void applyPattern(String newPattern)
          Sets the pattern.
 Object clone()
          Overrides Cloneable
 boolean equals(Object obj)
          Equality comparision between two message format objects
 StringBuffer format(Object[] source, StringBuffer result, FieldPosition ignore)
          Returns pattern with formatted objects.
 StringBuffer format(Object source, StringBuffer result, FieldPosition ignore)
          Formats an object to produce a string.
static String format(String pattern, Object[] arguments)
          Convenience routine.
 Format[] getFormats()
          Gets formats that were set with setFormats.
 Locale getLocale()
          Gets the locale.
 int hashCode()
          Generates a hash code for the message format object.
 Object[] parse(String source)
          Parses the string.
 Object[] parse(String source, ParsePosition status)
          Parses the string.
 Object parseObject(String text, ParsePosition status)
          Parses the string.
 void setFormat(int variable, Format newFormat)
          Set a format to be used on a variable in the pattern.
 void setFormats(Format[] newFormats)
          Sets formats to use on parameters.
 void setLocale(Locale theLocale)
          Constructs with the specified pattern and formats for the arguments in that pattern.
 String toPattern()
          Gets the pattern.
 
Methods inherited from class java.text.Format
format, parseObject
 
Methods inherited from class java.lang.Object
finalize, getClass, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

MessageFormat

public MessageFormat(String pattern)
Constructs with the specified pattern.
See Also:
applyPattern(java.lang.String)
Method Detail

setLocale

public void setLocale(Locale theLocale)
Constructs with the specified pattern and formats for the arguments in that pattern.

getLocale

public Locale getLocale()
Gets the locale. This locale is used for fetching default number or date format information.

applyPattern

public void applyPattern(String newPattern)
Sets the pattern. See the class description.

toPattern

public String toPattern()
Gets the pattern. See the class description.

setFormats

public void setFormats(Format[] newFormats)
Sets formats to use on parameters. See the class description about format numbering.

setFormat

public void setFormat(int variable,
                      Format newFormat)
Set a format to be used on a variable in the pattern.
Parameters:
variable - the zero-based number of the variable in the format. This is not the argument number. If variable is out of range, an ArrayIndexOutOfBoundsException is thrown.
newFormat - the format to use for the specified variable

getFormats

public Format[] getFormats()
Gets formats that were set with setFormats. See the class description about format numbering.

format

public final StringBuffer format(Object[] source,
                                 StringBuffer result,
                                 FieldPosition ignore)
Returns pattern with formatted objects. If source is null, the original pattern is returned, if source contains null objects, the formatted result will substitute each argument with the string "null".
Parameters:
source - an array of objects to be formatted & substituted.
result - where text is appended.
ignore - no useful status is returned.

format

public static String format(String pattern,
                            Object[] arguments)
Convenience routine. Avoids explicit creation of MessageFormat, but doesn't allow future optimizations.

format

public final StringBuffer format(Object source,
                                 StringBuffer result,
                                 FieldPosition ignore)
Description copied from class: Format
Formats an object to produce a string. Subclasses will implement for particular object, such as:
 StringBuffer format (Number obj, StringBuffer toAppendTo)
 Number parse (String str)
 
These general routines allow polymorphic parsing and formatting for objects such as the MessageFormat.
Overrides:
format in class Format
Tags copied from class: Format
Parameters:
obj - The object to format
toAppendTo - where the text is to be appended
pos - On input: an alignment field, if desired. On output: the offsets of the alignment field.
Returns:
the value passed in as toAppendTo (this allows chaining, as with StringBuffer.append())
Throws:
IllegalArgumentException - when the Format cannot format the given object.
See Also:
MessageFormat, FieldPosition

parse

public Object[] parse(String source,
                      ParsePosition status)
Parses the string.

Caveats: The parse may fail in a number of circumstances. For example:

When the parse fails, use ParsePosition.getErrorIndex() to find out where in the string did the parsing failed. The returned error index is the starting offset of the sub-patterns that the string is comparing with. For example, if the parsing string "AAA {0} BBB" is comparing against the pattern "AAD {0} BBB", the error index is 0. When an error occurs, the call to this method will return null. If the soruce is null, return an empty array.

parse

public Object[] parse(String source)
               throws ParseException
Parses the string. Does not yet handle recursion (where the substituted strings contain {n} references.)
Throws:
ParseException - if the string can't be parsed.

parseObject

public Object parseObject(String text,
                          ParsePosition status)
Parses the string. Does not yet handle recursion (where the substituted strings contain %n references.)
Overrides:
parseObject in class Format
Tags copied from class: Format
Parameters:
status - Input-Output parameter.

Before calling, set status.index to the offset you want to start parsing at in the source. After calling, status.index is the end of the text you parsed. If error occurs, index is unchanged.

When parsing, leading whitespace is discarded (with successful parse), while trailing whitespace is left as is.

Example: Parsing "_12_xy" (where _ represents a space) for a number, with index == 0 will result in the number 12, with status.index updated to 3 (just before the second space). Parsing a second time will result in a ParseException since "xy" is not a number, and leave index at 3.

Subclasses will typically supply specific parse methods that return different types of values. Since methods can't overload on return types, these will typically be named "parse", while this polymorphic method will always be called parseObject. Any parse method that does not take a status should throw ParseException when no text in the required format is at the start position.

Returns:
Object parsed from string. In case of error, returns null.
See Also:
ParsePosition

clone

public Object clone()
Overrides Cloneable
Overrides:
clone in class Format
Tags copied from class: Object
Returns:
a clone of this instance.
Throws:
CloneNotSupportedException - if the object's class does not support the Cloneable interface. Subclasses that override the clone method can also throw this exception to indicate that an instance cannot be cloned.
OutOfMemoryError - if there is not enough memory.
See Also:
Cloneable

equals

public boolean equals(Object obj)
Equality comparision between two message format objects
Overrides:
equals in class Object
Tags copied from class: Object
Parameters:
obj - the reference object with which to compare.
Returns:
true if this object is the same as the obj argument; false otherwise.
See Also:
Boolean.hashCode(), Hashtable

hashCode

public int hashCode()
Generates a hash code for the message format object.
Overrides:
hashCode in class Object
Tags copied from class: Object
Returns:
a hash code value for this object.
See Also:
Object.equals(java.lang.Object), Hashtable

JavaTM 2 Platform
Standard Edition

Submit a bug or feature
Java, Java 2D, and JDBC are a trademarks or registered trademarks of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-1999 Sun Microsystems, Inc. 901 San Antonio Road,
Palo Alto, California, 94303, U.S.A. All Rights Reserved.