public final class MessageFormatUtil extends Object
MessageFormat
工具类,常用于国际化 .MessageFormat
,
Format
public static String format(String pattern, Object... arguments)
MessageFormat.format(String, Object...)
格式化.
MessageFormatUtil.format("name=张三{0}a{1}", "jin", "xin") = "name=张三jinaxin" MessageFormatUtil.format("name=张三{0,number}a{1}", 5, "xin") = "name=张三5axin" MessageFormatUtil.format("name=张三{0,date,yyyy-MM-dd}a{1}", DateUtil.toDate("2000", DatePattern.yyyy), "xin") = "name=张三2000-01-01axin"
格式: ArgumentIndex[,FormatType[,FormatStyle]]
占位符有三种方式书写方式:
- {argumentIndex}: 0-9之间的数字,表示要格式化对象数据在参数数组中的索引号
- {argumentIndex,formatType}:参数的格式化类型
- {argumentIndex,formatType,FormatStyle}: 格式化的样式,它的值必须是与格式化类型相匹配的合法模式、或表示合法模式的字符串.
字段 说明 ArgumentIndex 是从0开始的入参位置索引 FormatType 指定使用不同的Format子类对入参进行格式化处理。值范围如下:
字段 说明 number 调用 NumberFormat
进行格式化date 调用 DateFormat
进行格式化time 调用 DateFormat
进行格式化choice 调用 ChoiceFormat
进行格式化FormatStyle 设置FormatType中使用的格式化样式。
值范围如下: short,medium,long,full,integer,currency,percent,SubformPattern(子格式模式,形如#.##)注意: FormatType 和 FormatStyle 主要用于对日期时间、数字、百分比等进行格式化。
示例——将数字1.23格式为1.2: double num = 1.23; String str = MessageFormatUtil.format("{0,number,#.#}", num);
- 两个单引号才表示一个单引号,仅写一个单引号将被忽略。
- 单引号会使其后面的占位符均失效,导致直接输出占位符。
MessageFormatUtil.format("{0}{1}", 1, 2); // 结果12 MessageFormatUtil.format("'{0}{1}", 1, 2); // 结果{0}{1} MessageFormatUtil.format("'{0}'{1}", 1, 2); // 结果{0} 因此可以用于输出左花括号(单写左花括号会报错,而单写右花括号将正常输出) MessageFormatUtil.format("'{'{0}}", 2); // 结果{2
pattern
- 模式参数arguments
- 动态参数pattern
是null,抛出 NullPointerException
Copyright © 2008-2019 by feilong