2

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

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

它至少应该支持java.util.Map,但也欢迎可以处理 bean 或递归查找或在映射/对象列表中查找的东西。

建议?

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

4

3 回答 3

5

Commons LangStrSubstitutor几乎可以满足您的要求

于 2009-12-09T11:28:48.867 回答
1

使用StringTemplate来实现expand

void expand(String template, Map<String,String> map) {
    StringTemplate st = new StringTemplate(template);

    for (Map.Entry<String, String> attribute : map) {
       st.setAttribute(attribute.getKey(), attribute.getValue());
    }

    return st.toString();
} 
于 2009-12-09T10:22:00.783 回答
0

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

于 2009-12-09T10:34:42.097 回答