我最近对Java中的这种功能感兴趣,作为具有可变数量参数的函数.这是一个非常酷的功能.但我很感兴趣:
void method(int x, String.. args) {
// Do something
}
Run Code Online (Sandbox Code Playgroud)
这是如何在运行时级别实际实现的?我想到的是,当我们打电话时:
method(4, "Hello", "World!");
Run Code Online (Sandbox Code Playgroud)
最后两个参数在内部转换为一个数组,并传递给该方法.我对此是正确的,或者JVM实际上是否在堆栈中引用了字符串,而不仅仅是对数组的一个引用?
Evg*_*eev 12
它在编译时实现.您将方法编译为字节码为
varargs method(I[Ljava/lang/String;)V
...
Run Code Online (Sandbox Code Playgroud)
这相当于
void method(int x, String[] args) {
...
Run Code Online (Sandbox Code Playgroud)
与varargs国旗.
和
method(4, "Hello", "World!");
Run Code Online (Sandbox Code Playgroud)
编译为
method(4, new String[] {"Hello", "World!"});
Run Code Online (Sandbox Code Playgroud)
这样的方法转换为
void method(int x, String[] args) {
}
Run Code Online (Sandbox Code Playgroud)
和它的召唤
method(4, "Hello", "World!");
Run Code Online (Sandbox Code Playgroud)
转换为
method(4, new String[]{"Hello", "World!"});
Run Code Online (Sandbox Code Playgroud)
注意最后一个调用可以直接写。这在覆盖可变参数方法时很有用:
@Override
void method(int x, String... args) {
String[] newArgs=new String[];
... // fill new args; then
super.method(newArgs);
}
Run Code Online (Sandbox Code Playgroud)