Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get string.format to complain at compile time

The compiler has access to the format string AND the required types and parameters. So I assume there would be some way to indicate missing parameters for the varargs ... even if only for a subset of cases. Is there someway for eclipse or another ide to indicate that the varargs passed might cause a problem at runtime ?

like image 446
mafalda Avatar asked Jan 17 '11 21:01

mafalda


People also ask

Can you format strings in Java?

In java, String format() method returns a formatted string using the given locale, specified format string, and arguments. We can concatenate the strings using this method and at the same time, we can format the output concatenated string.

Does format return a string?

The Java String. format() method returns the formatted string by a given locale, format, and argument. If the locale is not specified in the String.

What method is used to format strings?

The String format() Method.


2 Answers

It looks as if FindBugs can solve your problem. There are some warning categories related to format strings.

  • http://www.google.com/search?q=%2Bjava+%2Bprintf+%2Bfindbugs
  • http://findbugs.sourceforge.net/bugDescriptions.html#VA_FORMAT_STRING_MISSING_ARGUMENT
like image 164
Roland Illig Avatar answered Oct 26 '22 15:10

Roland Illig


The Java compiler doesn't have any built-in semantic knowledge of StringFormat parameters, so it can't check on these at compile time. For all it knows, StringFormat is just another class and String.format is just another method, and the given format string is just another string like any other.

But yeah, I feel your pain, having come across these same problems in the past couple days. What they ought to have done is make it 'less careful' about the number of parameters, and just leave trailing %s markers un-replaced.

like image 42
jk. Avatar answered Oct 26 '22 14:10

jk.