Java String.format
默默地忽略传递的额外参数,这些参数未在格式字符串中使用,但如果传递的参数较少或无效则会失败。有没有办法在传递更多参数时处理这种情况?
如果参数多于格式说明符,则忽略额外参数
private static void doStuff(Stuff stuff, String details, Object... args) {
if(stuff.someCondition()) {
try {
details = String.format("Details: " + details, args);
} catch (Exception ex) { //No Exception thrown when args are not used by
String arguments = Arrays.stream(args)
.map(Objects::toString)
.collect(joining(";"));
details = String.format("Details: %s Args: %s", details, arguments);
}
}
stuff.process(details);
}
private static void foo() {
Stuff stuff = new Stuff();
doStuff(stuff, "blah blah %s ", "blah"); // No exception, works as expected
doStuff(stuff, "blah blah %s %s", "blah"); // Fails as expected and args are printed
doStuff(stuff, "blah blah %s", "blah", "blah"); // Silently ignores. How to handle this case?
}
答案 0 :(得分:0)
采用不同的方法而不计算或解析%
。虽然效率不高。
public static String safeFormat(String formatStr, Object... args) {
String result = String.format(formatStr, args);
List<Object> objects = Arrays.asList(args);
//https://commons.apache.org/proper/commons-lang/javadocs/api-3.7/org/apache/commons/lang3/mutable/MutableBoolean.html
MutableBoolean isCalled = new MutableBoolean(false);
objects.add(new Object(){
@Override
public String toString() {
isCalled.setTrue();
return "";
}
});
//noinspection ResultOfMethodCallIgnored
String.format(formatStr+" %s", objects.toArray());
if(isCalled.isFalse()) {
throw new IllegalArgumentException("Not all arguments used by formatter");
}
return result;
}