Java 語法糖(四): Varargs (變長參數(shù))

正文

java 支持變長參數(shù), 那么這個功能是如何實現(xiàn)的呢?
先寫段簡單的程序嘗試一下

package com.fake;

public class VarArgsTest {

    public static void main(String... args) {
        System.out.println(args.getClass());
    }
}

運行結(jié)果如下圖所示


運行結(jié)果.png

名為 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(...) 有何不同。

圖片.png

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

圖片.png

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

圖片.png

下面還有一段補充

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)容(有兩張圖)

圖一.png

圖一里的紅框部分相當于執(zhí)行了

f1(new int[]{999, 888, 777})
圖二.png

圖二里的紅框部分相當于執(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ù)組元素 的過程給補上。

參考文章

  1. https://www.benf.org/other/cfr/varargs.html
  2. https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.6
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容