//可以编译后,通过IDEA的jclasslib插件查看字节码
public class StackOperateTest {
public void print() {
Object obj = new Object();
//String info = obj.toString();
obj.toString();
}
public void foo() {
bar();
}
public long bar() {
return 0;
}
public long nextIndex() {
return index ++;
}
private long index = 0;
}
条件跳转指令通常和比较指令结合使用,在条件跳转执行前,一般可以先用比较指令进行栈顶元素的准备,然后进行条件跳转
条件跳转指令:ifeq,iflt,ifle,ifne,ifgt,ifge,ifnull,ifnonnull,这些指令都接收两个字节的操作数,用于跳转的位置(16位符号整数作为当前位置的offset)
它们统一含义为:弹出栈顶元素,测试它是否满足某一条件,如果满足条件,则跳转到给定位置
注:
//可通过jclasslib插件查看字节码
public void ifcompare1() {
int i = 10;
int j = 20;
System.out.println(i < j);
}
public void ifcompare2() {
short s1 = 9;
byte b1 = 20;
System.out.println(s1 > b1);
}
public void ifcompare3() {
Object obj1 = new Object();
Object obj2 = new Object();
System.out.println(obj1 == obj2);
System.out.println(obj1 != obj2);
}
//ifcompare3字节码
0 new #10 <java/lang/Object>
3 dup
4 invokespecial #1 <java/lang/Object.<init>>
7 astore_1
8 new #10 <java/lang/Object>
11 dup
12 invokespecial #1 <java/lang/Object.<init>>
15 astore_2
16 getstatic #4 <java/lang/System.out>
19 aload_1
20 aload_2
21 if_acmpne 28 (+7)
24 iconst_1
25 goto 29 (+4)
28 iconst_0
29 invokevirtual #5 <java/io/PrintStream.println>
32 getstatic #4 <java/lang/System.out>
35 aload_1
36 aload_2
37 if_acmpeq 44 (+7) //比较相等时跳转,见上图
40 iconst_1
41 goto 45 (+4)
44 iconst_0
45 invokevirtual #5 <java/io/PrintStream.println>
48 return
public void switch1(int select) {
int num;
switch (select) {
case 1:
num = 10;
break;
case 2:
num = 20;
break;
case 3:
num = 30;
break;
default:
num = 40;
}
}
//--字节码
0 iload_1
1 tableswitch 1 to 3 1: 28 (+27) //switch... case 1-3
2: 34 (+33)
3: 40 (+39)
default: 46 (+45)
28 bipush 10
30 istore_2
31 goto 49 (+18)
34 bipush 20
36 istore_2
37 goto 49 (+12)
40 bipush 30
42 istore_2
43 goto 49 (+6)
46 bipush 40
48 istore_2
49 return
public void switch2(int select) {
int num;
switch (select) {
case 100:
num = 10;
break;
case 500:
num = 20;
break;
case 200:
num = 30;
break;
default:
num = 40;
}
}
//字节码
0 iload_1
1 lookupswitch 3
100: 36 (+35)
200: 48 (+47)
500: 42 (+41)
default: 54 (+53)
36 bipush 10
38 istore_2
39 goto 57 (+18)
42 bipush 20
44 istore_2
45 goto 57 (+12)
48 bipush 30
50 istore_2
51 goto 57 (+6)
54 bipush 40
56 istore_2
57 return