我发现自己经常想要在其中编写带有参数占位符的可重用字符串,几乎与您在SQL PreparedStatement中找到的完全相同.
这是一个例子
private static final String warning = "You requested ? but were assigned ? instead.";
public void addWarning(Element E, String requested, String actual){
warning.addParam(0, requested);
warning.addParam(1, actual);
e.setText(warning);
//warning.reset() or something, I haven't sorted that out yet.
}
Run Code Online (Sandbox Code Playgroud)
Java中是否存在类似的内容?或者,有没有更好的方法来解决这样的问题?
我真正想问的是:这是理想的吗?
Gar*_*all 62
String.format()从Java 5开始,您可以使用String.format参数化字符串.例:
String fs;
fs = String.format("The value of the float " +
"variable is %f, while " +
"the value of the " +
"integer variable is %d, " +
" and the string is %s",
floatVar, intVar, stringVar);
Run Code Online (Sandbox Code Playgroud)
请参见http://docs.oracle.com/javase/tutorial/java/data/strings.html
或者,您可以创建一个包装器,String以便做更多花哨的事情.
MessageFormat根据Max的评论和Affe的回答,您可以使用MessageFormat类本地化参数化的String .
Kei*_*all 10
你可以用String.format.就像是:
String message = String.format("You requested %2$s but were assigned %1$s", "foo", "bar");
Run Code Online (Sandbox Code Playgroud)
会产生
"You requested bar but were assigned foo"
Run Code Online (Sandbox Code Playgroud)