有没有在Java中替代java.lang.String.format()并使用通用占位符的方法?

huangapple go评论58阅读模式
英文:

Is there an alternate to java.lang.String.format() in java to use generic placeholder

问题

slf4j Logger具有清晰的格式化语法(使用花括号)

org.slf4j.Logger.error("Invalid value1={} for value2={}", value1, value1)

下面的方法是否有类似的替代方法?我想要一个通用的占位符({}),而不是特定于类型的占位符。

String.format("Invalid value1=%d for value2=%d", value1, value1)
英文:

slf4j Logger has a formatter syntax that is clean. ( Use of curly braces )

org.slf4j.Logger.error("Invalid value1={} for value2={}", value1, value1)

Is the below method has a similar alternative? I want a generic ({}) instead of type-specific place-holder.

String.format("Invalid value1=%d for value2=%d", value1, value1)

答案1

得分: 5

你可以使用 String.format%s

String.format("Invalid value1=%s for value2=%s", value1, value1)

%s 对所有类型都适用,就像你的日志记录器中的 {} 一样。它会将任何给定的参数转换为字符串,这似乎正是你的要求。

英文:

You can use String.format with %s.

String.format("Invalid value1=%s for value2=%s", value1, value1)

%s works for all types, just as {} does in your logger. It converts any given argument to a string, which seems to be exactly your requirement.

答案2

得分: 1

你可以使用MessageFormat,如果你愿意的话,不过你需要指定参数编号:

MessageFormat.format("Invalid value1={0} for value2={1}", value1, value2);
英文:

You could use MessageFormat if you prefer, although you would need to specify argument numbers:

MessageFormat.format("Invalid value1={0} for value2={1}", value1, value2);

huangapple
  • 本文由 发表于 2020年9月3日 15:47:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/63719078.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定