MessageFormat详解

原创博客不易,请勿随意转载。请注明来源

源码解析

用法详解

用法详解

  • MessageFormat,使用静态方法format()的时候效率不如字符串拼接

初始化

初始化详解

  1. 使用静态方法format()
String result = MessageFormat.format("{0} -> {1}", "Hello", "world")  // Hello -> world
  1. 创建公用对象使用
MessageFormat messageFormat = new MessageFormat("{0} -> {1}");
// 使用的时候需要传入Object类型的数组
String result =  messageFormat.format(new Object[]{"Hello", "world"});
  • 分析
  1. 最常用最简单的是直接使用静态方法
  2. 创建公用对象使用效率更高
// 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说明
shortshort数字
mediumTODO 待补充
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");
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值