我似乎回想起一个Apache Commons或类似的API,它允许你使用属性扩展替换内联字符串,类似于Freemarker或Velocity(或JSP容器)完成此操作而不必拖入这些工具。谁能回忆一下这个API是什么?显然,名称不正确,但构造看起来像这样:
Person person = ...;
String expanded = SomeAPI.expand(
"Hi ${name}, you are ${age} years old today!",
person);
我不是在寻找关于如何实现这一点的其他建议(例如使用Formatter),而只是现有的API。
答案 0 :(得分:3)
MessageFormat
可能是您正在寻找的内容:
final MessageFormat format = new MessageFormat("Hi {0}, you are {1, number, #} years old today!");
final String expanded = format.format(new Object[]{person.getName(), person.getAge()});
还有一个类似String.format
的C:
final String expanded = String.format("Hi %1s, you are %2s years old today!", person.getName(), person.getAge());
测试:
public static void main(String[] args) {
final MessageFormat format = new MessageFormat("Hi {0}, you are {1,number,#} years old today!");
System.out.println(format.format(new Object[]{"Name", 15}));
System.out.println(String.format("Hi %1s, you are %2s years old today!", "Name", 15));
}
输出:
Hi Name, you are 15 years old today!
Hi Name, you are 15 years old today!
答案 1 :(得分:0)