I’m using String.format method of Java API to log something. My method is like:
public static void log(String message, Object... params){
System.out.println(String.format(message, params));
}
However the problem is, if the user sends a message that has % character somewhere in it, it throws exception. Here’s a scenario:
log("SELECT * FROM my WHERE name like '%six%'");
and Java looks for something to replace %s (that’s ok) and %' (oops). I want to fix that. Because there there are no params and %s will be lost and %' causes exception.
One solution can be message.replace("%", "%%") but I’m not sure it is an elegant solution or not.
loghas no idea whether a given%is meant as a format specifier or as a percent sign. Consider the following example:Is that
"test%s","%stest", or an error?Therefore, the problem will have to be addressed at the call site:
where
escape()is a function you’ll need to write that’ll replace all%with%%.Alternatively, the following can be used at the call site: