Java可变参数机制 基础类型转换为对象 assert机制
- 2016-06-23 20:38:00
- admin
- 原创 1767
一、Java可变参数机制
调用可变参数函数,编译器在调用处创建数组:
public static void main(String[] args) {
print("rtx", "feinenxiang");
}
编译代码:
public static void main(java.lang.String[]);
flags: ACC_PUBLIC, ACC_STATIC
Code:
stack=4, locals=1, args_size=1
0: iconst_2
1: anewarray #31 // class java/lang/String
4: dup
5: iconst_0
6: ldc #33 // String rtx
8: aastore
9: dup
10: iconst_1
11: ldc #35 // String feinenxiang
13: aastore
14: invokestatic #37 // Method print:([Ljava/lang/String;)V
可变参数通过数组实现,所以使用时像数组一样:
public static void print(String ...msgs) {
System.out.println(msgs.length);
}
编译代码:
public static void print(java.lang.String...);
flags: ACC_PUBLIC, ACC_STATIC, ACC_VARARGS
Code:
stack=2, locals=1, args_size=1
0: getstatic #16 // Field java/lang/System.out:Ljava/io/PrintStream;
3: aload_0
4: arraylength
5: invokevirtual #22 // Method java/io/PrintStream.println:(I)V
可变参数函数调用方式:
1、func(arg1, arg2, arg3);
2、func(new Type[]{arg1, arg2, arg3});
3、方式二比方式一更适合频繁调用;
4、支持0个参数,即创建长度是0的数组;
二、Java基础类型转换为对象
Integer intObj = 0;
Short shortObj = 0;
Object o = intObj;
System.out.println(o.equals(0));
编译后的代码:
0: iconst_0
1: invokestatic #16 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
4: astore_1
5: iconst_0
6: invokestatic #22 // Method java/lang/Short.valueOf:(S)Ljava/lang/Short;
9: astore_2
10: aload_1
11: astore_3
12: getstatic #27 // Field java/lang/System.out:Ljava/io/PrintStream;
15: aload_3
16: iconst_0
17: invokestatic #16 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
20: invokevirtual #33 // Method java/lang/Object.equals:(Ljava/lang/Object;)Z
23: invokevirtual #37 // Method java/io/PrintStream.println:(Z)V
三、assert机制
assert false: "first assert";
编译后的代码:
0: getstatic #16 // Field $assertionsDisabled:Z
3: ifne 16
6: new #122 // class java/lang/AssertionError
9: dup
10: ldc #124 // String first assert
12: invokespecial #126 // Method java/lang/AssertionError."<init>":(Ljava/lang/Object;)V
15: athrow
补充说明:
1、assert本质是一种抛异常,因为是Error,所以不受try和catch管制;
2、-ea启动断言,-da关闭断言,默认关闭断言;