Is there a general string substitution function similar to sl4fj?
With sl4fj if I want to construct a string message there is a nice approach which makes use of substitutions. For instance, it might be something like:
logger.info("Action {} occured on object {}.", objectA.getAction(), objectB);
If there are more than a few substitutions required then it is something like:
logger.info("Action {} occured on object {} with outcome {}.",
new Object[]{objectA.getAction(), objectB, outcome});
My question is: Is there a generic way for me to create a string (and not just a slf4j log message)? Something like:
String str = someMethod("Action {} occured on object {}.", objectA.getAction(), objectB);
or
String str = someMethod("Action {} occured on object {} with outcome {}.",
new Object[]{objectA.getAction(), objectB, outcome});
If it is in the standard Java library, what would that "someMethod" be?
String.format
String str = String.format("Action %s occured on object %s.",
objectA.getAction(), objectB);
Or
String str = String.format("Action %s occured on object %s with outcome %s.",
new Object[]{objectA.getAction(), objectB, outcome});
You can also use numeric positions, for example to switch the parameters around:
String str = String.format("Action %2$s occured on object %1$s.",
objectA.getAction(), objectB);
You can use String.format or MessageFormat.format
E.g.,
MessageFormat.format("A sample value {1} with a sample string {0}",
new Object[] {"first", 1});
or simply
MessageFormat.format("A sample value {1} with a sample string {0}", "first", 1);