最近沉迷于java反编译,经常看到iconst_1指令,见得多了,也让我对它感到很好奇,它是不是就是固定代表int 1啊?
做个小测试,从11到0,看看它们分别对应字节码什么?
public class Bytecode {
public void ByteCode() {
int eleven = 11;
int ten = 10;
int nine = 9;
int eight = 8;
int seven = 7;
int six = 6;
int five = 5;
int four = 4;
int three = 3;
int two = 2;
int one = 1;
int zero = 0;
}
}
在JDK1.8.0_151的环境下,使用javac编译上面的文件,得到Bytecode.class文件,然后利用javap反编译这份字节码文件。
很有意思,从11到9,用到了istore_1, istor_2, istore_3, 其余都是istore
从11到6,都是bipush, 从5到0,分别用到了iconst_5, iconst_4, iconst_3, iconst_2, iconst_1, iconst_0
为了排除顺序的关系,我们把代码调整成这样:
public class Bytecode {
public void ByteCode() {
int zero = 0;
int one = 1;
int two = 2;
int three = 3;
int four = 4;
int five = 5;
int six = 6;
int seven = 7;
int eight = 8;
int nine = 9;
int ten = 10;
int eleven = 11;
}
}
然后再编译,反编译看看结果:
看来,istore_1,istore_2,istore_3是和顺序有关,但是iconst_0到iconst_5是精准的对应0到5。
再做个这样的对比:
public class Bytecode {
public void ByteCode() {
int one = 1;
long lone = 1L;
byte bone = (byte)1;
double done = 1.0;
}
}
编译,然后反编译,看看结果。
各自对应都不同,倒是byte被“换成”int让我对jvm又有了无限的遐想了。
到这里,基本可以印证了,iconst_1就是对应int 1
【总结】:
iconst_0对应int 0
iconst_1对应int 1
iconst_2对应int 2
iconst_3对应int 3
iconst_4对应int 4
iconst_5对应int 5
lconst_1对应long 1L
【问题】:为什么不归纳dconst_1对应1.0呢?
【思考】:小伙伴们试试boolean T = true, boolean F = false编译后对应什么字节码,保证有惊喜哦!^_^