java中的模板字面量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51874352/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 00:17:10  来源:igfitidea点击:

Template literals in java

javatemplates

提问by fudy

in javascript I can write the follow code:

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

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

the output is

输出是

status is 1, data key is 2

Is there any libs provide the way to do it in java, providing the following function?

是否有任何库提供在 java 中执行此操作的方法,提供以下功能?

String xxxFunction(Map map, String template)

please note the usage of ${response.data.key}, map in map

请注意${response.data.key}地图中地图的用法

回答by M?nh Quy?t Nguy?n

You can try StrSubstitutorfrom Apache common text

您可以从 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);

You can find a download link / dependency here

您可以在此处找到下载链接/依赖项

回答by pvpkiran

You can make use of String.format

你可以利用 String.format

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