Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a general string substitution function similar to sl4fj?

Tags:

java

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?

like image 263
kmccoy Avatar asked Feb 20 '11 15:02

kmccoy


People also ask

How do you add a variable to a string in Java?

Using the + operator is the most common way to concatenate two strings in Java. You can provide either a variable, a number, or a String literal (which is always surrounded by double quotes). Be sure to add a space so that when the combined string is printed, its words are separated properly.


1 Answers

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); 
like image 109
The Scrum Meister Avatar answered Sep 17 '22 16:09

The Scrum Meister