We have method that looks like this :
public String getCommandString(Object...args) {
return this.code + " " + String.format(this.pattern, args);
}
Where this.code:int and this.pattern:String.
This method is usually called like this :
// cmd.code = 20
// cmd.pattern = "%1$s = %2$d"
String str = cmd.getCommandString("foo", 3); // -> "20 foo = 3"
and other string patterns (this is for a very simple text-based server-client program)
Now, is it possible for pattern to take into account a variable number of arguments, such as
// cmd.code = 20
// cmd.pattern = ???
String s1 = cmd.getCommandString("a", "b", "c"); // -> 20 a b c
String s2 = cmd.getCommandString("Hello", "world"); // -> 20 Hello world
String s3 = cmd.getCommandString("1", "2, "3", "4", "5", "6"); // -> 20 1 2 3 4 5 6
Assuming perhaps that each argument is of the same type (strings)? Or do I have to override the method and format the string manually? More specifically, I’m looking for a generic string pattern to format a variable number of arguments (of the same type). I remember making such a thing in C, but is this possible in Java?
The functionality you are asking for, if I understand it correctly, does not exist. Here is the javadoc section from the
Formatterclass:What you are asking for is a way to construct a pattern that will accept an arbitrary number of arguments and use tham all. The problem is that the
Formatterclass can only associate format specifiers with arguments either explicitly, relatively, or ordinarily. In each of these cases, the number of forma specifiers is fixed. There is no construct in which you can repeat or loop a format specifier. The relative technique looks promising, but there is no way to nest, or loop, it.