Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
199 views
in Technique[技术] by (71.8m points)

Parameterized Strings in Java

I find myself very frequently wanting to write reusable strings with parameter placeholders in them, almost exactly like what you'd find in an SQL PreparedStatement.

Here's an example

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.
}

Does something like this exist already in Java ? Or, is there a better way to address something like this ?

What I'm really asking: is this ideal ?

question from:https://stackoverflow.com/questions/10019162/parameterized-strings-in-java

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

String.format()

Since Java 5, you can use String.format to parametrize Strings. Example:

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);

See http://docs.oracle.com/javase/tutorial/java/data/strings.html

Alternatively, you could just create a wrapper for the String to do something more fancy.

MessageFormat

Per the comment by Max and answer by Affe, you can localize your parameterized String with the MessageFormat class.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...