原创博客不易,请勿随意转载。请注明来源
源码解析
用法详解
用法详解
- MessageFormat,使用静态方法format()的时候效率不如字符串拼接
初始化
初始化详解
- 使用静态方法format()
String result = MessageFormat.format("{0} -> {1}", "Hello", "world") // Hello -> world
- 创建公用对象使用
MessageFormat messageFormat = new MessageFormat("{0} -> {1}");
// 使用的时候需要传入Object类型的数组
String result = messageFormat.format(new Object[]{"Hello", "world"});
- 分析
- 最常用最简单的是直接使用静态方法
- 创建公用对象使用效率更高
// MessageFormat.format() 源码。每次使用都要new一个MessageFormat对象
public static String format(String pattern, Object ... arguments) {
MessageFormat temp = new MessageFormat(pattern);
return temp.format(arguments);
}
使用方式
使用详解
使用
- pattern 格式
在format中可以用那些pattern格式
格式 | 示例 |
---|---|
{argumentIndex} | my name is {0}. |
{argumentIndex, FormatType} | i’m {0, number} years old. |
{argumentIndex, FormatType} | Today is {0, date, yyyy-MM-dd HH:mm:ss}. |
- FormatType
定义传入内容的类型
type | 说明 |
---|---|
number | 数值,style可以是下表的,也可以是0.0等 |
date | 日期,可以传入date,默认是yyyy-MM-dd格式,可以在style中指定格式,如yyyy-MM-dd HH:mm:ss |
time | 时间,暂未测试 TODO 待补充 |
choice | 需要使用ChoiceFormat TODO 待补充 |
- FormatStyle
对应FormatType的样式
style | 说明 |
---|---|
short | short数字 |
medium | TODO 待补充 |
long | |
full | |
integer | |
currency | |
percent | |
SubFormatPattern | 子模式,例如 0.0、yyyy-MM-dd |
注意点
- 原字符串使用到左大括号的需要转义,使用单引号将转义内容括起来,右小括号无需转义
String result = MessageFormat.format("My '{'name} is {0}", "joe");
- 原字符串有单引号,需要使用两个单引号来表示
String result = MessageFormat.format("My ''name'' is {0}", "joe");