String与MessageFormat的说明
一、两者的使用场景
String.Format:用于布局调整和对齐,用于数字、字符串和日期/时间数据的通用格式,以及特定于地区的输出。
MessageFormat.Format:以与语言无关的方式生成连接的消息。
二、两者的性能比较
MeesageFormat由于是一个在先分析的指定位置插入相应的值,性能要好于采用正则表达式查找占位符的String.format方法。MessageFormat > String
三、以下是异常的情况
String message = MessageFormat.format(“name={0}, age={}”, 25, “huhx”); // java.lang.IllegalArgumentException: can’t parse argument number:
String string = String.format(“name=%s, age=%d”, “huhx”); // java.util.MissingFormatArgumentException: Format specifier ‘%d’
两者的实现原理
我们通过下面的简单的例子来分析两者的原理:
public void messageFormat() {
String string = String.format("name=%s, age=%d", "huhx", 25);
String message = MessageFormat.format("name={1}, age={0}, {1}", 25, "huhx");
System.out.println(string);
System.out.println(message);
}
// name=huhx, age=25
// name=huhx, age=25, huhx
一、String.format的实现原理
String.format内部的实现是一个Formatter,使用了正则表达式来查找占位数据的。我们在这里贴出它实现的源代码。
1 public Formatter format(Locale l, String format, Object ... args) {
2 ensureOpen();
3 // index of last argument referenced
4 int last = -1;
5 // last ordinary index
6 int lasto = -1;
7
8 FormatString[] fsa = parse(format);
9 for (int i = 0; i < fsa.length; i++) {
10 FormatString fs = fsa[i];
11 int index = fs.index();
12 try {
13 switch (index) {
14 case -2: // fixed string, "%n", or "%%"
15 fs.print(null, l);
16 break;
17 case -1: // relative index
18 if (last < 0 || (args != null && last > args.length - 1))
19 throw new MissingFormatArgumentException(fs.toString());
20 fs.print((args == null ? null : args[last]), l);
21 break;
22 case 0: // ordinary index
23 lasto++;
24 last = lasto;
25 if (args != null && lasto > args.length - 1)
26 throw new MissingFormatArgumentException(fs.toString());
27 fs.print((args == null ? null : args[lasto]), l);
28 break;
29 default: // explicit index
30 last = index - 1;
31 if (args != null && last > args.length - 1)
32 throw new MissingFormatArgumentException(fs.toString());
33 fs.print((args == null ? null : args[last]), l);
34 break;
35 }//需要获取资料的朋友请加Q君样:290194256*
36 } catch (IOException x

本文介绍了Java中String.format和MessageFormat.format的区别与性能,重点分析了两者在异常情况下的表现及实现原理。String.format依赖正则表达式,而MessageFormat.format采用预分析定位值,性能更优。此外,文章提供了详细的源码分析。
最低0.47元/天 解锁文章
1232

被折叠的 条评论
为什么被折叠?



