字符串扩展实用程序

时间:2013-03-07 17:20:26

标签: java velocity freemarker

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

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

我不是在寻找关于如何实现这一点的其他建议(例如使用Formatter),而只是现有的API。

2 个答案:

答案 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)

这应该可以使用Apache Commons LangBeanUtils

来实现
  StrSubstitutor sub = new StrSubstitutor(new BeanMap(person));

  String replaced = sub.replace("Hi ${name}, you are ${age} years old today!");