Java 基础 -- MessageFormat

MessageFormat提供了一种以语言无关的方式生成串联消息的方法。使用它来构造显示给最终用户的消息。

MessageFormat接受一组对象,对它们进行格式化,然后将格式化后的字符串插入到模式的适当位置。

注意:MessageFormat与其他Format类的不同之处在于,您使用它的一个构造函数(而不是使用getInstance风格的工厂方法)创建MessageFormat对象。工厂方法不是必需的,因为MessageFormat本身不实现特定于语言环境的行为。任何特定于语言环境的行为都由您提供的模式以及用于插入参数的子格式定义。

模式及其解释

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

String中,一对单引号可以用来引用除单引号以外的任意字符。例如,模式字符串" '{0}' " 代表字符串" {0} “,而不是FormatElement。在整个字符串中,单引号本身必须用双单引号 ' '表示。例如,模式字符串 " '{' '}' " 被解释为'{ (引号开始和左花括号),"(单引号)和}'(右花括号和引号结束)的序列,而不是'{''}'(左、右花括号加引号): 表示字符串”{'}“,而不是”{}"

SubformatPattern由其相应的子格式解释,并且应用子格式相关的模式规则。例如,模式字符串{1,number,$'#',##}($'#',##SubformatPattern)将生成一个带引号的数字格式,其结果如:“$#31,45”。有关详细信息,请参阅每个Format子类文档。

任何不匹配的引号在给定模式的末尾被视为关闭。例如,模式字符串"'{0}“被视为模式”'{0}'"。

非引号模式中的任何花括号都必须是平衡的。例如,“ab {0} de"和"ab '}' de"是有效的模式,但"ab {0'}' de”、“ab } de"和”' '{' '"不是。

ArgumentIndex值是一个非负整数,使用数字’0’到’9’写入,并表示传入 format方法的参数数组或parse方法返回的结果数组的索引。

FormatTypeFormatStyle值用于为Format元素创建Format实例。下表显示了这些值如何映射到Format实例。未在表中显示的组合是非法的。SubformatPattern必须是所使用的Format子类的有效模式字符串。

用法

下面是一些用法示例。在真正的国际化程序中,消息格式模式和其他静态字符串当然是从资源包中获得的。其他参数将在运行时动态确定。

第一个示例使用静态方法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 10:27:05 on 2023-5-31, there was a disturbance in the Force on planet 7.

猜你喜欢

转载自blog.csdn.net/chinusyan/article/details/130962793