Reputation: 6706
I seem to recall an Apache Commons or similar API that would allow you to replace a string inline using property expansion similar to how Freemarker or Velocity (or a JSP container for that matter) accomplish this without having to drag in those tools. Can anyone recall what this API is? Obviously, the names are incorrect but the construct looks something like this:
Person person = ...;
String expanded = SomeAPI.expand(
"Hi ${name}, you are ${age} years old today!",
person);
I'm not looking for other suggestions on how to accomplish this (using a Formatter for example), just the existing API.
Upvotes: 0
Views: 1121
Reputation: 6706
This should do the trick using Apache Commons Lang and BeanUtils:
StrSubstitutor sub = new StrSubstitutor(new BeanMap(person));
String replaced = sub.replace("Hi ${name}, you are ${age} years old today!");
Upvotes: 1
Reputation: 61128
MessageFormat
may be what you're looking for:
final MessageFormat format = new MessageFormat("Hi {0}, you are {1, number, #} years old today!");
final String expanded = format.format(new Object[]{person.getName(), person.getAge()});
There is also a C like String.format
:
final String expanded = String.format("Hi %1s, you are %2s years old today!", person.getName(), person.getAge());
Test:
public static void main(String[] args) {
final MessageFormat format = new MessageFormat("Hi {0}, you are {1,number,#} years old today!");
System.out.println(format.format(new Object[]{"Name", 15}));
System.out.println(String.format("Hi %1s, you are %2s years old today!", "Name", 15));
}
Output:
Hi Name, you are 15 years old today!
Hi Name, you are 15 years old today!
Upvotes: 3