正文
java 支持變長參數(shù), 那么這個功能是如何實現(xiàn)的呢?
先寫段簡單的程序嘗試一下
package com.fake;
public class VarArgsTest {
public static void main(String... args) {
System.out.println(args.getClass());
}
}
運行結(jié)果如下圖所示

名為 args 的參數(shù)的類型看起來就是 String[]。
那么我們在 VarArgsTest 類中寫兩個函數(shù)試一試 varargs 和普通的數(shù)組參數(shù)有何不同(新的代碼如下)。
package com.fake;
public class VarArgsTest {
private void f1(int... args) {
}
private void f2(int[] args) {
}
public static void main(String[] args) {
new VarArgsTest().f1(999, 888, 777);
new VarArgsTest().f2(new int[]{999, 888, 777});
}
}
build 之后,在 IntelliJ IDEA 里借助 Bytecode viewer 插件看一看 f1(...) 和 f2(...) 有何不同。

對比之后,不難發(fā)現(xiàn),兩個函數(shù)的 access flag 是不同的(但是 入?yún)㈩愋?/strong> 以及 返回值類型 都是完全相同的)

前往 https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.6 會看到 access flags 的描述

下面還有一段補充
The ACC_VARARGS flag indicates that this method takes a variable number of arguments at the source code level. A method declared to take a variable number of arguments must be compiled with the ACC_VARARGS flag set to 1. All other methods must be compiled with the ACC_VARARGS flag set to 0.
那么當我們調(diào)用 varargs 方法時,編譯器會幫我們把參數(shù)轉(zhuǎn)化為數(shù)組嗎?
實踐出真知,我們來試一試。
我在剛才的 VarArgsTest 類中寫了一個 main 方法
public static void main(String[] args) {
new VarArgsTest().f1(999, 888, 777);
new VarArgsTest().f2(new int[]{999, 888, 777});
}
繼續(xù)借助 Bytecode viewer 插件,看一看字節(jié)碼中對應的內(nèi)容(有兩張圖)

圖一里的紅框部分相當于執(zhí)行了
f1(new int[]{999, 888, 777})

圖二里的紅框部分相當于執(zhí)行了
f2(new int[]{999, 888, 777})
這么一對比,就會發(fā)現(xiàn),編譯器會幫忙把
new VarArgsTest().f1(999, 888, 777); 轉(zhuǎn)化為
new VarArgsTest().f1(new int[]{999, 888, 777});
由此可以推測,在調(diào)用 varargs 方法時,編譯器會自動把 創(chuàng)建數(shù)組 以及 填寫數(shù)組元素 的過程給補上。