Pass array to variable parameter method

I'm using JCommander in a project.

Its documentation defines its parse method to be like

parse

public void parse(String... args)
    Parse and validate the command line parameters.

so, it accepts a variable number of individual String arguments (to my understanding.)

However, my args are currently stored in an array of strings,

public static void main(String[] args) {
  CommandTemplate template = new CommandTemplate();
  JCommander jc = new JCommander(template);

  jc.parse(args); // <---  effectively what I'd like to accomplish.
}
Jon Skeet
people
quotationmark

That code will already work fine. The args parameter of parse is already of type String[] - the String... syntax just means that the compiler is allowed to convert this:

parse("foo", "bar", "baz");

into

parse(new String[] { "foo", "bar", "baz" });

implicitly. If you pass a value which is already a string array, it doesn't need to do anything.

The JLS doesn't have a section specifically about this, but section 8.4.1 (method formal parameters) has quite a bit of information on variable arity methods including:

Invocations of a variable arity method may contain more actual argument expressions than formal parameters. All the actual argument expressions that do not correspond to the formal parameters preceding the variable arity parameter will be evaluated and the results stored into an array that will be passed to the method invocation (ยง15.12.4.2).

people

See more on this question at Stackoverflow