0

我似乎记得一个 Apache Commons 或类似的 API,它允许您使用属性扩展替换字符串内联,类似于 Freemarker 或 Velocity(或就此而言的 JSP 容器)完成此操作而无需拖入这些工具。谁能记得这个 API 是什么?显然,名称不正确,但构造看起来像这样:

Person person = ...;
String expanded = SomeAPI.expand(
                  "Hi ${name}, you are ${age} years old today!", 
                  person);

我不是在寻找有关如何完成此任务的其他建议(例如使用 Formatter),只是在寻找现有的 API。

4

2 回答 2

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()});

还有一个像这样的C String.format

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!
于 2013-03-07T17:31:48.233 回答
1

这应该使用 Apache Commons LangBeanUtils来解决问题:

  StrSubstitutor sub = new StrSubstitutor(new BeanMap(person));

  String replaced = sub.replace("Hi ${name}, you are ${age} years old today!");
于 2013-03-07T19:04:08.293 回答