Java 语法糖 - 可变参数
Java About 2,130 words本质
可变参数本质就是数组。
Java 代码
可以看到String... args
可变参数可以直接赋值给String[]
数组。
public class Test3 {
public static void foo(String... args) {
String[] arr = args;
System.out.println(arr);
}
public static void main(String[] args) {
foo("a", "b"); // 等价于foo(new String[]{"a", "b"});
}
}
字节码
可以看到:
foo
方法的LocalVariableTable
中0
号槽位是args
,签名也是数组。
main
方法中使用的是anewarray
字节码,等价于foo(new String[]{"a", "b"})
。
对于foo()
等价于foo(new String[]{})
。
public static void foo(java.lang.String...);
descriptor: ([Ljava/lang/String;)V
flags: (0x0089) ACC_PUBLIC, ACC_STATIC, ACC_VARARGS
Code:
stack=2, locals=2, args_size=1
0: aload_0
1: astore_1
2: getstatic #2 // Field java/lang/System.out:Ljava/io/PrintStream;
5: aload_1
6: invokevirtual #3 // Method java/io/PrintStream.println:(Ljava/lang/Object;)V
9: return
LineNumberTable:
line 6: 0
line 7: 2
line 8: 9
LocalVariableTable:
Start Length Slot Name Signature
0 10 0 args [Ljava/lang/String;
2 8 1 arr [Ljava/lang/String;
MethodParameters:
Name Flags
args
public static void main(java.lang.String[]);
descriptor: ([Ljava/lang/String;)V
flags: (0x0009) ACC_PUBLIC, ACC_STATIC
Code:
stack=4, locals=1, args_size=1
0: iconst_2
1: anewarray #4 // class java/lang/String
4: dup
5: iconst_0
6: ldc #5 // String a
8: aastore
9: dup
10: iconst_1
11: ldc #6 // String b
13: aastore
14: invokestatic #7 // Method foo:([Ljava/lang/String;)V
17: return
LineNumberTable:
line 11: 0
line 13: 17
LocalVariableTable:
Start Length Slot Name Signature
0 18 0 args [Ljava/lang/String;
MethodParameters:
Name Flags
args
Views: 1,359 · Posted: 2022-04-21
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb/LiteNote扫描下方二维码关注公众号和小程序↓↓↓
Loading...