JVM如何实现varargs? [英] How does JVM implement the varargs?

查看:137
本文介绍了JVM如何实现varargs?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近对Java中的这样一个功能感兴趣,作为具有可变数量参数的函数。这是一个非常酷的功能。但我很感兴趣:

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!");

最后两个参数在内部转换为数组,并传递给方法。我是对的,或者JVM实际上是在向字符串引用堆栈,而不只是对数组的一个引用?

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?

推荐答案

它在编译时实现。您将方法编译为字节码为

It is implemented at compile time level. You method is compiled to bytecode as

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

相当于

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

varargs flag。

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

编译为

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

这篇关于JVM如何实现varargs?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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