占位符在我们开发过程中通用的使用场景主要用于应答信息中,应答信息的配置一般会配置于数据库中或者properties配置文件中。
在properties文件中我们可以使用占位符来进行动态的替换,例如在properties文件中我们配置了:
ErrorMessage=This is Error Message : {0}.
以下代码模拟获取"ErrorMessage "的配置,然后使用想要的值去替换{0}。
String pattern = "ErrorMessage=This is Error Message : {0}.";
String returnStr = MessageFormat.format(pattern, "000100");
System.out.println(returnStr);
java.text.MessageFormat.format静态方法
方法定义:
StringMessageFormat.format(Stringpattern, Object...args)
输入参数pattern为MessageFormat模式参数。
MessageFormat模式
格式: {ArgumentIndex[,FormatType[,FormatStyle]]}
ArgumentIndex ,是从0开始的入参位置索引。
FormatType ,指定使用不同的Format子类对入参进行格式化处理。值范围如下:
number:调用NumberFormat进行格式化
date:调用DateFormat进行格式化
time:调用DateFormat进行格式化
choice:调用ChoiceFormat进行格式化
choice示例:
MessageFormat form = new MessageFormat("The disk \"{1}\" contains {0}.");
double[] filelimits = {0,1,2};
String[] filepart = {"no files","one file","{0,number} files"};
ChoiceFormat fileform = new ChoiceFormat(filelimits, filepart);
form.setFormatByArgumentIndex(0, fileform);
int fileCount = 123;
String diskName = "MyDisk";
Object[] testArgs = {new Long(fileCount), diskName};
System.out.println(form.format(testArgs));
FormatType ,设置FormatType中使用的格式化样式。值范围如下:
short,medium,long,full,integer,currency,percent,SubformPattern(子格式模式,形如#.##)
注意: FormatType 和 FormatStyle 主要用于对日期时间、数字、百分比等进行格式化。
示例:
double num = 1.234;
String str = MessageFormat.format("Format Number: {0,number,#.##} .", num);
System.out.println(str);
注意点:
1. 两个单引号才表示一个单引号,仅写一个单引号将被忽略。
2. 单引号会使其后面的占位符均失效,导致直接输出占位符。
MessageFormat.format("{0}{1}", 1, 2); // 结果12
MessageFormat.format("'{0}{1}", 1, 2); // 结果{0}{1}
MessageFormat.format("'{0}'{1}", 1, 2); // 结果{0}2
MessageFormat.format("'{'{0}", 2); // 结果{2
3. 如果传入多个参数,但实际需要替换的占位符没有那么多,程序并不会报错。
MessageFormat.format("First:{0},Second:{1},third.", 1,2,3);
性能问题
由于静态方法 MessageFormat.format 内部是
public static String format(String pattern, Object ... arguments)
{
MessageFormat temp = new MessageFormat(pattern);
return temp.format(arguments);
}
因此若要多次格式同一个模式的字符串,那么创建一个MessageFormat实例在执行格式化操作比较好些。