问题
I was converting a Groovy codebase into Java and forgot to change
public static void main(String... args) {
to
public static void main(String args[]) {
and compiled and ran the project all this time only to be surprised only now that this is legal Java 8 code.
I understand that Java 8 Varargs makes it possible for a function to have arbitrary number of arguments, "compacting them into an Array" depending on their position on the method call.
But the way functions with String... args
and String[] args
are called syntactically differently:
void function1 (String[] args) {}
function1({"one", "two", "three"});
void function2 (String... args) {}
function2("one", "two", "three");
So how is String... args
as legal as String args[]
when grabbing params from the terminal?
Edit:
azurefrog linked an answer to a different question that is great. I wanted to mention another answer where the comments provide the answer I was looking for:
Why doesn't Java's main use a variable length argument list?
Comment 1: Interesting. Judging by the other answers/comments, I guess this new main declaration syntax was added with Java 1.5. So the Java runtime determines, based on your main method declaration, whether to pass the strings directly to the main or build an array first?
Comment 2: No, it always builds an array. String... args == String[]
args, as far as the called method is concerned. The parameter is an array in any case
That's the question I had. Sorry if it was asked poorly.
回答1:
It's been legal since varargs were added to the language, I believe. The syntax for calling them explicitly differs, sure, but command-line arguments are passed in not by other Java code but "magically."
JLS 12.1.4 specifies this:
The method main must be declared public, static, and void. It must specify a formal parameter (§8.4.1) whose declared type is array of String. Therefore, either of the following declarations is acceptable:
public static void main(String[] args) public static void main(String... args)
回答2:
As you already said, at compile-time all varargs...
are swapped out with arrays[]
.
Thus the java compiler recognizes your vararg parameters and puts them into an array.
See @Louis_Wasserman 's answer for the JSL quote.
https://docs.oracle.com/javase/tutorial/java/javaOO/arguments.html --- the Java Tutorial
来源:https://stackoverflow.com/questions/36803342/java-8-varargs-on-main-function-signature