Java 数组参数声明语法“..."是如何实现的?工作? [英] How does the Java array argument declaration syntax "..." work?

查看:43
本文介绍了Java 数组参数声明语法“..."是如何实现的?工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

写java有段时间了,今天遇到如下声明:

I have been writing java for a while, and today I encountered the following declaration:

public static void main(String... args) {

}

注意数组声明中的dot dot dot",而不是通常的括号[].显然它有效.事实上,我写了一个小测试并验证了它的工作原理.所以,我把java语法拉出来看看这个参数声明的语法在哪里,但没有找到任何东西.

Note the "dot dot dot" in the array declaration, rather than the usual bracket []. Clearly it works. In fact I wrote a small test and verified it works. So, I pulled the java grammar to see where this syntax of argument declaration is, but did not find anything.

那么对于那里的专家来说,这是如何工作的?它是语法的一部分吗?另外,虽然我可以像这样声明函数,但我不能像这样在函数体内声明数组.

So to the experts out there, how does this work? Is it part of the grammar? Also, while I can declare function like this, I can't declare an array within a function's body like this.

无论如何,你知道任何地方有这方面的记录吗?这是好奇心,也许不值得为此投入任何时间,但我被难住了.

Anyway, do you know of any place that has this documented. It is curiosity, and perhaps not worth of any time invested in it, but I was stumped.

推荐答案

查看 Java 语言规范,第三版,第 8 章(类).埋在那里的是这个金块:

Check out the Java Language Specification, Third Edition, Chapter 8 (Classes). Buried in there is this nugget:

如果最后一个形参是T类型的可变元参数,则认为定义了一个T[]类型的形参.该方法则是可变元方法.否则,它是一个固定的元数方法.可变参数方法的调用可能包含比形式参数更多的实际参数表达式.所有与变量 arity 参数前的形参不对应的实参表达式都将被评估,并将结果存储到一个数组中,该数组将传递给方法调用(第 15.12.4.2 节).

If the last formal parameter is a variable arity parameter of type T, it is considered to define a formal parameter of type T[]. The method is then a variable arity method. Otherwise, it is a fixed arity method. 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).

基本上,任何方法调用的最后一个参数都可以有 T....如果有,则将其转换为 T[].

Basically, the last parameter of any method call can have T.... If it has that, it is converted to T[].

所以基本上,你拥有的是一种复制更传统的奇特方式

So basically, what you have is a fancy way of reproducing the more traditional

String[] args

这篇关于Java 数组参数声明语法“..."是如何实现的?工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆