in javascript I can write the follow code:
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?
String xxxFunction(Map map, String template)
please note the usage of ${response.data.key}
, map in map
Template literals are literals delimited with backtick (`) characters, allowing for multi-line strings, for string interpolation with embedded expressions, and for special constructs called tagged templates.
${} is a placeholder that is used in template literals. You can use any valid JavaScript expression such as variable, arithmetic operation, function call, and others inside ${}. The expression used inside ${} is executed at runtime, and its output is passed as a string to template literals.
When you use regular template literals, your input is passed to a default function that concatenates it into a single string. An interesting thing is that you can change it by preceding the template literal with your function name that acts as a tag. By doing it, you create a tagged template.
In addition to its syntactical differences there are two very specific advantages to using template literals: Multi-line strings: A single string can span two or more lines. Expression Interpolation: Javascript variables and expressions can be inserted directly in the string.
You can make use of String.format
String template = "status is %s, data key is %s"
String result = String.format(template, status, key);
You can try StrSubstitutor from Apache common text
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With