Strsubstitutor
Another suitable option for simple variable substitutions is the StrSubstitutor
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 downside of this class is having to use a separate library.
But it is very useful, for example, if you want to let the user type a parameterized template where you will provide 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 be like this:
/temp/logs/acessos-${data}.log.${numeroArquivo}
And then the system applies the variables data
and numeroArquivo
when saving the log.
It is possible to modify the prefix and suffix of the variables using another constructor of the class StrSubstitutor
, so there’s no need to be stuck to the pattern ${
and }
.
This would be a case closer to what is intended in the question.
Messageformat
Beyond the standard of Formatter
or String.format()
, there is a slightly more advanced option that has support even to pluralize texts, which is more suitable if the intention is to parameterize the texts of the application and do Internationalization and Localization.
This is about the 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.
I know, but some function should return a new string. I need something similar to Preparedstatement that parameterizes the SQL String
– Skywalker
I am aware that String are immutable. I want to parameterize a String.
– Skywalker