gpt4 book ai didi

java - 更严格的 String.format 不会忽略额外的参数?

转载 作者:行者123 更新时间:2023-12-03 21:26:03 27 4
gpt4 key购买 nike

Java的String.format静默忽略传递的额外参数,这些参数不在格式字符串中使用,但如果传递的参数较少或无效,则会失败。当传递更多参数时,有没有办法处理这种情况?

If there are more arguments than format specifiers, the extra arguments are ignored



https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#format-java.lang.String-java.lang.Object...-
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?
}

最佳答案

采取不同的方法而不计算或解析 % .虽然不是一个有效的。

public static String safeFormat(String formatStr, Object... 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 String.format(formatStr, args);
}

关于java - 更严格的 String.format 不会忽略额外的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48233220/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com