Java魔法堂:初探MessageFormat.format和ChoiceFormat

时间:2022-04-22
本文章向大家介绍Java魔法堂:初探MessageFormat.format和ChoiceFormat,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

一、前言                              

  刚开始从.net的转向java的时候总觉得 String.format 用得不习惯,希望格式模版会这样 {0}, this is {1}'s cat.{1},this is {0}'s dog. 而不是 %1$s,this is %2$s's cat.%2$s,this is %1$s's dog. 。后来发现 java.text.MessageFormat.format 可以满足我这个小小的愿望。

二、静态方法 java.text.MessageFormat.format

  方法定义:

String MessageFormat.format(String fmt, Object...args)

  入参fmt为MessageFormat模式参数。

三、MessageFormat模式                      

  格式:  ArgumentIndex[,FormatType[,FormatStyle]]

ArgumentIndex ,是从0开始的入参位置索引。

FormatType ,指定使用不同的Format子类对入参进行格式化处理。值范围如下:

     number:调用NumberFormat进行格式化

     date:调用DateFormat进行格式化

     time:调用DateFormat进行格式化

     choice:调用ChoiceFormat进行格式化

FormatType ,设置FormatType中使用的格式化样式。值范围如下:

    short,medium,long,full,integer,currency,percent,SubformPattern(子格式模式,形如#.##)

  注意: FormatType 和 FormatStyle 主要用于对日期时间、数字、百分比等进行格式化。

  示例——将数字1.23格式为1.2:

double num = 1.23;
String str = MessageFormat.format("{0,number,#.#}", num);

四、MessageFormat注意点                    

  1. 两个单引号才表示一个单引号,仅写一个单引号将被忽略。

  2. 单引号会使其后面的占位符均失效,导致直接输出占位符。

MessageFormat.format("{0}{1}", 1, 2); // 结果12
MessageFormat.format("'{0}{1}", 1, 2); // 结果{0}{1}
MessageFormat.format("'{0}'{1}", 1, 2); // 结果{0}

因此可以用于输出左花括号(单写左花括号会报错,而单写右花括号将正常输出)

MessageFormat.format("'{'{0}}", 2); // 结果{2

因此前言中的示例应该写为

{0}, this is {1}''s cat.{1},this is {0}''s dog.

五、类层级关系                                

                                         |-- java.text.MessageFormat

顶层抽象类java.text.Format—|                                         |--java.text.ChoiceFormat

                                         |--java.text.NumberFormat—|

             |               |--java.text.DecimalFormat

               |

                                         |--java.text.DateFormat—java.text.SimpleDateFormat

   1. DecimalFormat

       用于格式化十进制实数。通过格式字符串来自定义格式化类型,舍入方式为half-even(四舍五入)。

       格式化模式: 正数子模式;负数子模式 ,如 0.00;-0.00 ,简写为 0.00 

       模式中的占位符:

,代表该为位为数字,若不存在则用0填充

,代表该为位为数字

,代表分隔符, 如模式为 #,# ,那么格式化10时会返回1,0

   2. ChoiceFormat

    相当于以数字为键,字符串为值的键值对。分别使用一组double类型的数组作为键,一组String类型的数组作为值,两数组相同索引值的元素作为一对。

    示例——基本用法

double[] limit = {0,1,3};
String[] format = {"hello0", "hello1", "hello3"};
ChoiceFormat cf = new ChoiceFormat(limit, format);
for(int i = 0; i < 4; ++i){
  System.out.println(cf.format(i));
}
/* 输出
 * hello0
 * hello1
 * hello0
 * hello3
 */

   注意:当找不到对应的键值对时,则使用第一或最后一对键值对。

   示例——结合MessageFormat使用

double[] limit = {0, 1};
String[] format = {"Hello0", "Hello1{1}"};
ChoiceFormat cf = new ChoiceFormat(limit, format);
MessageFormat mf = new MessageFormat("{0}");
mf.setFormatByArgumentIndex(0, cf);
for (int i = 0; i < 2; ++i){
    System.out.println(mf.format(new Object[]{new Integer(i), new Integer(i+1)}));
}
/* 输出
 * Hello0
 * Hello12
 */

六、性能问题                                  

  由于静态方法 MessageFormat.format 内部是

public static String format(String pattern, Object ... arguments)   
{  
    MessageFormat temp = new MessageFormat(pattern);  
    return temp.format(arguments);  
}  

  因此若要多次格式同一个模式的字符串,那么创建一个MessageFormat实例在执行格式化操作比较好些。

七、总结                                  

  对于简单的格式化或字符串组装, MessageFormat.format方法 使用更方便些,但要格式化处理更丰富的话要是用 String.format方法 吧!  

八、参考

  http://zqc-0101.iteye.com/blog/114014