StrSubstitutor
Another suitable option for simple variable overrides is StrSubstitutor
" of Apache Commons.
Example:
Map valuesMap = HashMap();
valuesMap.put("animal", "quick brown fox");
valuesMap.put("target", "lazy dog");
String templateString = "The ${animal} jumped over the ${target}.";
StrSubstitutor sub = new StrSubstitutor(valuesMap);
String resolvedString = sub.replace(templateString);
The disadvantage of this class is having to use a separate library.
But it is very useful, for example, if you want to let the user enter a parametrized template where you will supply the value of the variables and do not want advanced formatting options .
An example is if you want to let the user enter a path pattern for a rotating log file. It could look like this:
/temp/logs/acessos-${data}.log.${numeroArquivo}
And then the system applies the variables data
and numeroArquivo
when saving the log.
You can change the prefix and suffix of the variables using another constructor of class StrSubstitutor
, so you do not have to be stuck with the ${
and }
pattern.
This would be a case closer to what you want in the question.
MessageFormat
In addition to the Formatter
or String.format()
standard, there is a slightly more advanced option that is even supported to pluralize texts, which is more appropriate if the intention is to parameterize the texts of the application and do internationalization and localization.
This is MessageFormat
.
Example:
int planet = 7;
String event = "a disturbance in the Force";
String result = MessageFormat.format( "At {1,time} on {1,date}, there was {2} on planet {0,number,integer}.",
planet, new Date(), event);
Considerations
Note that these classes have specific applications and their use is unnecessary in the simplest and most common use cases.