What this article will cover?
MessageFormat in Java, MessageFormat in java example, MessageFormat java API, MessageFormat java class and how to use MessageFormat in java
MessageFormat in Java
MessageFormat is a class that helps to format a message String. It also helps to substitute objects into the predefined position in the message String.
The MessageFormat class constructs textual messages using a formatting pattern string. Conceptually, the class functions much like printf() in C. Syntactically, however, it is quite different. A MessageFormat object uses a pattern string; formatted arguments are placed into the pattern string to produce a resulting string. Arguments are delimited by matching sets of curly braces and may include additional information about how that data should be formatted. For example, consider the following code:
String message =
"Boot of server {0}began at {1, time}on {1, date, full}.";
MessageFormat boot = new MessageFormat(message);
Date now = new Date();
Object[] arguments = {"luna3", now};
System.out.println(boot.format(arguments));
This code produces the following output:
The boot of server luna3 began at 11:13:22 AM on Monday, March 03, 1997.
Each of the arguments is numbered and includes an optional type and an optional style. In the example above, {1, date, full} indicates that the argument at index 1 in the argument array should be formatted using a DateFormat object with the FULL style. The allowed types and styles are:
Type | Object | available Styles |
---|---|---|
date | DateFormat | short, medium, long, full, pattern |
number | NumberFormat | integer, percent, currency, pattern |
time | DateFormat | short, medium, long, full, pattern |
choice | ChoiceFormat | pattern |
For the date and time types, the styles correspond to the styles, or lengths, of the resulting date and time strings. We can also specify a date or time pattern string as we would for creating a SimpleDateFormat object. For the number type, the styles correspond to formatting normal numbers, percentage values, and currency values. We can also specify a number pattern string as we would for creating a DecimalFormat object. For the choice type, we can specify a choice pattern as we would for creating a ChoiceFormat object. If no type is specified, the argument should be a string.
The following example shows how to use a choice format pattern with a MessageFormat:
Object[] arguments = {new Integer(1)};
String grammar = "At last count, {0}server{0, choice, 0#s|1#|1<s}
{0, choice, 0#were|1#was|1<were}booted.";
MessageFormat booted = new MessageFormat(grammar);
System.out.println(booted.format(arguments));
arguments[0] = new Integer(2);
System.out.println(booted.format(arguments));
This example produces the following output:
At last count, 1 server was booted.
At last count, 2 servers were booted.
As an alternative to specifying all of the formattings in the pattern string, we can use an array of Format objects to format the arguments. We can specify this array using setFormats().Note We create MessageFormat objects directly, rather than through factory methods. This is because MessageFormat does not implement any locale-specific behavior. To produce properly internationalized output, the pattern string that is used to construct a MessageFormat should come from a ResourceBundle instead of being embedded in the code.
MessageFormat in java example
If we want to display a message multiple times, MessageFormat helps a lot. We can achieve the same by creating an object of MessageFormat class by giving the pattern string. Once the object has been created, we can call the format() method (defined in this class) with the array of objects to be formatted into the output message.
The same method can be applied if we want to format the message only one time. In that case, we need to call the format() method with a message or pattern string or an array of argument objects. They will be formatted and substitute for the message.
The message or pattern should clearly state where each argument should be a substitute. We can obtain this by digits enclosed in curly braces.
Example-
If the pattern is “{0}” it signifies that the first object needs to be substituted with a string. Similarly “{5}” signifies that the sixth object needs to be substituted with a string.
Just in case the object that needs to be inserted is not String, the JVM checks if the same is an instance of Date or Number or the subclass of Date or Number.
If they are an instance of Date or Number or the subclass of Date or Number, MessageFormat insert them with default DateFormat or NumberFormat.
If they are not an instance of Date or Number or the subclass of Date or Number, MessageFormat insert them by invoking the object’s toString() method to convert.
The applicable and default patterns are:
- date
- time
- number
- choice
They will be autoformatted as date, time, number and choice before substituting them into pattern String.
However, they need to be separated by a comma.
The class structure of MessageFormat java class is given as
public class java.text.MessageFormat extends java.text.Format{ // Public Constructor public MessageFormat(String pattern); // Class Methods public static String format(String pattern, Object[] arguments); // Public Instance Methods public void applyPattern(String newPattern); public Object clone(); // Overrides Format public boolean equals(Object obj); // Overrides Object public final StringBuffer format(Object[] source, StringBuffer result,FieldPosition ignore); public final StringBuffer format(Object source, StringBuffer result,FieldPosition ignore); // Defines Format public Format[] getFormats(); public Locale getLocale(); public int hashCode(); // Overrides Object public Object[] parse(String source, ParsePosition status); public Object[] parse(String source) throws ParseException; public Object parseObject(String text, ParsePosition status); // Defines Format public void setFormat(int variable, Format newFormat); public void setFormats(Format[] newFormats); public void setLocale(Locale theLocale); public String toPattern(); }
The details of the class structure are given as follows:
public MessageFormat(String pattern);
public MessageFormat(String pattern) constructor creates a MessageFormat with the given formatting pattern string.
Parameter
pattern – The pattern string.
public static String format(String pattern, Object[] arguments);
public static String format(String pattern, Object[] arguments) method is interesting.Calling this static method is equivalent to constructing a MessageFormat using the given formatting pattern string and asking it to format the given arguments with the format() method.
Parameter
pattern – The pattern string.
arguments – An array of arguments.
public void applyPattern(String newPattern);
public void applyPattern(String newPattern) method tells this MessageFormat to use the given formatting pattern to format and parse arguments.
Parameter
pattern – The pattern string.
public Object clone();
public Object clone() method creates a copy of this MessageFormat and then returns it.
This method returns a copy of this MessageFormat.
public boolean equals(Object obj);
public boolean equals(Object obj) method returns true if obj is an instance of MessageFormat and is equivalent to this MessageFormat.
This method returns true if the objects are equal; false if they are not.
Parameter
obj – The object to be compared with this object.
public final StringBuffer format(Object[] source, StringBuffer result,FieldPosition ignore);
public final StringBuffer format(Object[] source, StringBuffer result, FieldPosition ignore) method formats the given object and appends the result to the given StringBuffer. The method assumes that the given object is an array of arguments.
This method returns the given buffer result with the formatted representation of the object appended to it.
Parameter
source – The object to be formatted.
result – A StringBuffer on which to append the formatted information.
ignore – Ignored.
public final StringBuffer format(Object source, StringBuffer result,FieldPosition ignore);
public final StringBuffer format(Object source, StringBuffer result,FieldPosition ignore) method formats the given arguments in the object array and appends the result to the given StringBuffer.
This method returns the given buffer result with the formatted representation of the object array appended to it.
Parameter
source – The object array to be formatted.
result – A StringBuffer on which to append the formatted information.
ignore – Ignored.
public Format[] getFormats();
public Format[] getFormats() method returns the format objects that this MessageFormat uses. Note that formats are numbered according to the order in which they appear in the formatting pattern string, not according to their specified argument numbers.
This method returns an array of the formats used by this MessageFormat.
public Locale getLocale();
public Locale getLocale() method returns the locate for this MessageFormat. This locale is used to get default date, time, and number formatters.
This method returns the Locale of this MessageFormat
public int hashCode();
public int hashCode(); method returns a hashcode for this MessageFormat.
This method returns a hashcode for this object.
public Object[] parse(String source, ParsePosition status);
public Object[] parse(String source, ParsePosition status) method
This method returns an array of objects represented by the test starting at the given position.
Parameter
source – The string to be parsed.
status – A ParsePosition object that specifies a position in the string.
public Object[] parse(String source) throws ParseException;
public Object[] parse(String source) throws ParseException method parses arguments from the given string, which should be in the format given by the formatting pattern string of this MessageFormat. If the string is not correctly formatted, an exception is thrown.
This method returns an array of objects represented by the given string.
Parameter
source – The string to be parsed.
public Object parseObject(String text, ParsePosition status);
public Object parseObject(String text, ParsePosition status) method parses arguments from the given string, starting at the specified position. The string should be in the format given by the formatting pattern string of this MessageFormat.
This method returns an array of objects represented by the test starting at the given position.
Parameter
source – The string to be parsed.
status – A ParsePosition object that specifies a position in the string.
public void setFormat(int variable, Format newFormat);
public void setFormat(int variable, Format newFormat) method sets the Format object that is used for the given argument in the formatting pattern string.
Parameter
variable – The index of an argument in the pattern string.
newFormat – The format object to use.
public void setFormats(Format[] newFormats);
public void setFormats(Format[] newFormats) method sets the Format objects that format the arguments of this MessageFormat. Note formats are numbered according to the order in which they appear in the formatting pattern string, not according to their specified argument numbers.
Parameter
newFormats – The format objects to use.
public void setLocale(Locale theLocale);
public void setLocale(Locale theLocale) method sets the Locale object that generates the default date, time, and number format objects.
Parameter
theLocale – The new locale.
public String toPattern();
public String toPattern() method returns the pattern string of this MessageFormat.
Apart from these methods MessageFormat class also has inherited methods from class- Object. They are as follows:
- finalize()
- notifyAll()
- wait()
- wait(long, int)
- equals(Object)
- getClass()
- notify()
- toString()
- wait(long)
MessageFormat class also has inherited methods from Format. They are as follows:
- format(Object)
- parseObject(String)
This method returns the pattern string of this MessageFormat.
how to use this class?
This area also covers the message format java API.
MessageFormat is kind of Printf() function, we find in C language. MessageFormat supports the below functions:
public Object[] parse(String source, ParsePosition status); public Object[] parse(String source) throws ParseException; public Object parseObject(String text, ParsePosition status);
The parse() method enables us to parse an array of objects from a specified String. It is governed by the specified pattern.
public void setFormat(int variable, Format newFormat); public void setFormats(Format[] newFormats);
setFormat() method enables us to change the Format object in a particular position with a particular pattern.
public void applyPattern(String newPattern);
This method enables us to set a new pattern for the MessageFormat.
public String toPattern();
This method returns the current formatting pattern.
public void setLocale(Locale theLocale);
This method specifies that the MessageFormat should use a nondefault Locale. We can insert DateFormat and NumberFormat objects to format dates and numbers. We can use them for formatting the message as a pattern.
Reference:
Oracle MessageFormat