8

For composing error, logging or any other String messages the String.format(...) method can be used. Unfortunately this method isn't type safe, hence the follwoing source will throw an IllegalFormatException

String s = String.format("My message has %d characters !", "30");

Is there any other alternative for composing such messages, except of the StringBuilder class.

My personal opinion is that the composed message gets harder to read by using a StringBuilder instance.

My-Name-Is
  • 4,814
  • 10
  • 44
  • 84
  • 2
    Consider using a static analysis tool like [Findbugs](http://findbugs.sourceforge.net/bugDescriptions.html#VA_FORMAT_STRING_BAD_ARGUMENT). – McDowell Mar 01 '14 at 15:36
  • With Scala you can have this using macros: http://docs.scala-lang.org/overviews/macros/overview.html#a_complete_example though it probably would not work from Java. – Gábor Bakos Mar 01 '14 at 15:37
  • Check out my answer here - http://stackoverflow.com/questions/24769455/java-string-format-compile-time-error-checking-and-safer-alternative - it still is a slight work in progress – Christopher Rucinski Jul 15 '14 at 23:35

1 Answers1

7

Using String.format() with only the %s format specifier is effectively typesafe (type opaque might be a better term) since every object will implement a toString() method, and even null objects are handled.

Of course, you have little control over the actual format of the string if you are not implementingtoString()...

lreeder
  • 12,047
  • 2
  • 56
  • 65