How does JVM implement the varargs?

五迷三道 提交于 2019-11-28 07:36:45

问题


I recently got interested in such a feature in Java, as functions with variable number of arguments. 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?


回答1:


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.

And

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

is compiled as

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



回答2:


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:

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



回答3:


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.



来源:https://stackoverflow.com/questions/21746663/how-does-jvm-implement-the-varargs

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!