简体   繁体   English

JVM如何实现varargs?

[英]How does JVM implement the varargs?

I recently got interested in such a feature in Java, as functions with variable number of arguments. 我最近对Java中的这种功能感兴趣,作为具有可变数量参数的函数。 This is a very cool feature. 这是一个非常酷的功能。 But I'm interested: 但我很感兴趣:

void method(int x, String.. args) {
  // Do something
}

How is this actually implemented on the runtime level? 这是如何在运行时级别实际实现的? What comes to my mind, is that when we have a call: 我想到的是,当我们打电话时:

method(4, "Hello", "World!");

The last two arguments are internally transformed into an array, that is passed to the method. 最后两个参数在内部转换为一个数组,并传递给该方法。 Am I right about this, or the JVM actually pushes in the stack refereneces to the strings, not just one reference to the array? 我对此是正确的,或者JVM实际上是否在堆栈中引用了字符串,而不仅仅是对数组的一个引用?

It is implemented at compile time level. 它在编译时实现。 You method is compiled to bytecode as 您将方法编译为字节码为

varargs method(I[Ljava/lang/String;)V
...

which is equivalent to 这相当于

void method(int x, String[] args) {
...

with varargs flag. varargs标志。

And

method(4, "Hello", "World!");

is compiled as 编译为

method(4, new String[] {"Hello", "World!"});

such a method is converted into 这样的方法被转换成

void method(int x, String[] args) {
}

and its call 和它的电话

method(4, "Hello", "World!");

is converted into 转换成

method(4, new String[]{"Hello", "World!"});

Note that the last call can be written directly. 请注意,最后一次调用可以直接写入。 This is useful when overriding vararg methods: 这在覆盖vararg方法时很有用:

@Override
void method(int x, String... args) {
    String[] newArgs=new String[];
    ... // fill new args; then
    super.method(newArgs);
}

The last two arguments are internally transformed into an array, that is passed to the method. 最后两个参数在内部转换为一个数组,并传递给该方法。 Am I right about this, 我是对的,

Yes , Your understanding is correct. 是的 ,你的理解是正确的。 An array constructs and passes as a argument. 数组构造并作为参数传递。

To make sure that If you see the byte code of that call you can see the array there. 要确保如果看到该调用的字节代码,则可以在那里看到该数组。 An array creates and and passes to the destination. 数组创建并传递到目标。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM