MessageFormat与占位符使用

       占位符在我们开发过程中通用的使用场景主要用于应答信息中,应答信息的配置一般会配置于数据库中或者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)

输入参数patternMessageFormat模式参数。

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中使用的格式化样式。值范围如下:

    shortmediumlongfullintegercurrencypercentSubformPattern(子格式模式,形如#.##)

 注意: 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实例在执行格式化操作比较好些。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Hoking

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值