替换文本中的变量:建议?

我正在寻找一个很好的模板引擎或一小段代码来在Java中的字符串中扩展类似Ant的变量。 例:

String result = expand ("${firstName} ${familyName}", map); 

它应该至少支持java.util.Map但是也可以使用能够处理bean或递归查找或在地图/对象列表中查找的东西。

建议?

[编辑]回复TofuBeer:没有嵌套,只有{}内的有效Java标识符。 ${}以外的任何内容都应逐字复制。 $$应该变成$``. If that's not possible ${dollar} $``. If that's not possible ${dollar}应该扩展到一个$ (所以你可以表达15.00 $ )。

来自Commons Lang的 StrSubstitutor几乎可以满足您的要求

使用StringTemplate实现expand

 void expand(String template, Map map) { StringTemplate st = new StringTemplate(template); for (Map.Entry attribute : map) { st.setAttribute(attribute.getKey(), attribute.getValue()); } return st.toString(); } 

看看Freemarker och Velocity,它们都是模板引擎