Class MessageFormatter
- java.lang.Object
-
- com.ibm.icu.message2.MessageFormatter
-
public class MessageFormatter extends Object
Overview of
MessageFormatterIn ICU4J, the
MessageFormatterclass is the next iteration ofMessageFormat. This new version will build on the lessons learned from using MessageFormat for 25 years in various environments, when used directly or as a base for other public APIs.The effort to design a succesor to
MessageFormatwill result in a specification referred to as MessageFormat 2.0. The reasoning for this effort is shared in the “Why MessageFormat needs a successor” document.MessageFormat 2.0 will be more modular and easier to port and backport. It will also provide extension points via interfaces to allow users to supply new functions without having to modify the specification. ICU will eventually include support for new formatters, such as intervals, relative time, lists, measurement units, personal names, and more, as well as the ability for users to supply their own custom implementations. These will potentially support use cases like grammatical gender, inflection, markup regimes (such as those require for text-to-speech), and other complex message management needs.
The MessageFormat Working Group, which develops the new data model, semantics, and syntax, is hosted on GitHub. The current specification for the syntax and data model can be found here.
This technical preview implements enough functions for
MessageFormatterto be useful in many situations, but the final set of functions and the parameters accepted by those functions is not yet finalized.Examples
Basic usage
import static org.junit.Assert.assertEquals; import java.util.Date; import java.util.HashMap; import java.util.Locale; import java.util.Map; import com.ibm.icu.message2.MessageFormatter; @Test public void test() { final Locale enGb = Locale.forLanguageTag("en-GB"); Map<String, Object> arguments = new HashMap<>(); arguments.put("name", "John"); arguments.put("exp", new Date(2023 - 1900, 2, 27, 19, 42, 51)); // March 27, 2023, 7:42:51 PM MessageFormatter mf2 = MessageFormatter.builder() .setPattern("Hello {$name}, your card expires on {$exp :datetime year=numeric month=short day=numeric weekday=short}!") .setLocale(enGb) .build(); assertEquals( "Hello John, your card expires on Mon, 27 Mar 2023!", mf2.formatToString(arguments)); }Placeholder examples
Code to set runtime value for placeholder Examples of placeholder in message pattern arguments.put("name", "John"){$name}arguments.put("exp", new Date(…)){$exp :datetime skeleton=year=numeric month=short day=numeric weekday=short}
{$exp :datetime dateStyle=full}arguments.put("val", 3.141592653){$val}
{$val :number minimumFractionDigits=5}No argument for fixed values known at build time {|123456789.531| :number}Plural selection message
@Test public void testSelection() { final String message = ".match {$count :number}\n" + " 1 {{You have one notification.}}\n" + " * {{You have {$count} notifications.}}\n"; final Locale enGb = Locale.forLanguageTag("en-GB"); Map<String, Object> arguments = new HashMap<>(); MessageFormatter mf2 = MessageFormatter.builder() .setPattern(message) .setLocale(enGb) .build(); arguments.put("count", 1); assertEquals( "You have one notification.", mf2.formatToString(arguments)); arguments.put("count", 42); assertEquals( "You have 42 notifications.", mf2.formatToString(arguments)); }Built-in formatter functions
The tech preview implementation comes with formatter functions for numbers (
:number), date / time (:datetime,:date,:time), plural selectors (:numberwith options forpluralandordinalselection), and general selector (:string), very similar to whatMessageFormatoffers.The ICU test code covers most features, and has examples of how to make custom placeholder formatters; you can look for classes that implement
com.ibm.icu.message2.FunctionFactory(they are namedCustom*Test.java).The complete list of valid options for each function, and how they infulence the results, can be found at here.
- Status:
- Draft ICU 78.
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static classMessageFormatter.BidiIsolationDetermines how the mixtures of bidirectional text are converted to string.static classMessageFormatter.BuilderABuilderused to build instances ofMessageFormatter.static classMessageFormatter.ErrorHandlingBehaviorDetermines how the formatting errors will be handled at runtime.
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Deprecated Methods Modifier and Type Method Description static MessageFormatter.Builderbuilder()Creates a builder.FormattedMessageformat(Map<String,Object> arguments)Deprecated.This API is for technology preview only.StringformatToString(Map<String,Object> arguments)Formats a map of objects by iterating over the MessageFormat's pattern, with the plain text “as is” and the arguments replaced by the formatted objects.MessageFormatter.BidiIsolationgetBidiIsolation()Get theMessageFormatter.BidiIsolationalgorithm to use when formatting mixed message parts with mixed direction.MFDataModel.MessagegetDataModel()Deprecated.This API is for technology preview only.MessageFormatter.ErrorHandlingBehaviorgetErrorHandlingBehavior()Get theMessageFormatter.ErrorHandlingBehaviorto use when encountering errors in the currentMessageFormatter.LocalegetLocale()Get the locale to use for all the formatting and selections in the currentMessageFormatter.StringgetPattern()Get the pattern (the serialized message in MessageFormat 2 syntax) of the currentMessageFormatter.
-
-
-
Method Detail
-
builder
public static MessageFormatter.Builder builder()
Creates a builder.- Returns:
- the Builder.
- Status:
- Draft ICU 78.
-
getLocale
public Locale getLocale()
Get the locale to use for all the formatting and selections in the currentMessageFormatter.- Returns:
- the locale.
- Status:
- Draft ICU 78.
-
getErrorHandlingBehavior
public MessageFormatter.ErrorHandlingBehavior getErrorHandlingBehavior()
Get theMessageFormatter.ErrorHandlingBehaviorto use when encountering errors in the currentMessageFormatter.- Returns:
- the error handling behavior.
- Status:
- Draft ICU 78.
-
getBidiIsolation
public MessageFormatter.BidiIsolation getBidiIsolation()
Get theMessageFormatter.BidiIsolationalgorithm to use when formatting mixed message parts with mixed direction.- Returns:
- the bidi isolation algorithm.
- Status:
- Draft ICU 78.
-
getPattern
public String getPattern()
Get the pattern (the serialized message in MessageFormat 2 syntax) of the currentMessageFormatter.If the
MessageFormatterwas created from anMFDataModelthe this string is generated from that model.- Returns:
- the pattern.
- Status:
- Draft ICU 78.
-
getDataModel
@Deprecated public MFDataModel.Message getDataModel()
Deprecated.This API is for technology preview only.Give public access to the message data model.This data model is similar to the functionality we have today in
MessagePatternUtilmaybe even a bit more higher level.We can also imagine a model where one parses the string syntax, takes the data model, modifies it, and then uses that modified model to create a
MessageFormatter.- Returns:
- the data model.
- Status:
- Technology Preview. This API is still in the early stages of development. Use at your own risk.
-
formatToString
public String formatToString(Map<String,Object> arguments)
Formats a map of objects by iterating over the MessageFormat's pattern, with the plain text “as is” and the arguments replaced by the formatted objects.- Parameters:
arguments- a map of objects to be formatted and substituted.- Returns:
- the string representing the message with parameters replaced.
- Throws:
IllegalArgumentException- when something goes wrong (for example wrong argument type, or null arguments, etc.)- Status:
- Draft ICU 78.
-
format
@Deprecated public FormattedMessage format(Map<String,Object> arguments)
Deprecated.This API is for technology preview only.Not yet implemented: formats a map of objects by iterating over the MessageFormat's pattern, with the plain text “as is” and the arguments replaced by the formatted objects.- Parameters:
arguments- a map of objects to be formatted and substituted.- Returns:
- the
FormattedMessageclass representing the message with parameters replaced. - Status:
- Technology Preview. This API is still in the early stages of development. Use at your own risk.
-
-