JavaScript中的模板字面量

17

在JavaScript中,我可以编写以下代码:

response = {
    status: 1,
    data: {
        key : 2
    }
}
var result = `status is ${response.status}, data key is ${response.data.key}`
console.log(result);

输出结果为

status is 1, data key is 2

有没有Java库提供以下功能?

String xxxFunction(Map map, String template)
请注意在map中使用${response.data.key}的用法。
2个回答

23

您可以利用String.format

String template = "status is %s, data key is %s"
String result = String.format(template, status, key);

1
虽然这可能回答了问题,但您应该通过提供一些解释文本和进一步阅读的文档来扩展您的答案。 - hellow
3
不是同一件事情... - theMayer
@theMayer - 你是什么意思? - MasterJoe
3
@MasterJoe,string.format和模板字面值不是一回事,甚至远远不能与模板字面值相比。实际上,它就是你试图避免使用模板字面值的东西。因此,正确的答案是“Java不提供这个功能。”C#赢得了比赛。 - theMayer

3
你可以尝试使用Apache common text中的StrSubstitutor
 Map valuesMap = HashMap();
 valuesMap.put("animal", "quick brown fox");
 valuesMap.put("target", "lazy dog");
 String templateString = "The ${animal} jumps over the ${target}. ${undefined.number:-1234567890}.";
 StrSubstitutor sub = new StrSubstitutor(valuesMap);
 String resolvedString = sub.replace(templateString);

你可以在这里找到下载链接/依赖 这里


它允许基于条件的字符串替换吗? - Gaurav
你的需求是什么,@gaurav? - Mạnh Quyết Nguyễn
@Manh 我想根据if-else条件替换字符串。例如:https://github.com/antlr/stringtemplate4/blob/master/doc/templates.md#conditionals - Gaurav

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接