jvm对boolean类型的处理

xiaoxiao2022-06-12  23

   JVM对boolean类型的支持比较有意思,java虚拟机规范里这样说:   Although the Java virtual machine defines a boolean type, it only provides very limited support for it. There are no Java virtual machine instructions solely dedicated to operations on boolean values. Instead, expressions in the Java programming language that operate on boolean values are compiled to use values of the Java virtual machine int data type.

The Java virtual machine does directly support boolean arrays. Its newarray instruction enables creation of boolean arrays. Arrays of type boolean are accessed and modified using the byte array instructions baload and bastore.

  实际测试了一下,代码:

  

/** **@authorZangXT */ publicclassTest{ publicstaticvoidmain(String[]args){ booleanb=true; booleanb1=false; boolean[]bs={true,false,false,true}; int[]array=newint[3]; byte[]bytes=newbyte[3]; System.out.println(bs.getClass());System.out.println(array.getClass());System.out.println(bytes.getClass());}}

输出是:

class [Zclass [Iclass [B对于boolean数组类型,内部表示为[Z,和byte[]的[B还是有差别的.

看实际字节码操作:

 

 0:iconst_1  //true用1表示 1:istore_1    2:iconst_0  //false用0表示 3:istore_2 4:iconst_4 5:newarrayboolean //boolean数组 7:dup 8:iconst_0 9:iconst_1 10:bastore 11:dup 12:iconst_1 13:iconst_0 14:bastore 15:dup 16:iconst_2 17:iconst_0 18:bastore 19:dup 20:iconst_3 21:iconst_1 22:bastore 23:astore_3 24:iconst_3 25:newarrayint 27:astore4 29:iconst_3 30:newarraybyte 32:astore5

从上面可以看出对boolean数组的操作使用的是bastore,也就是操作byte 数组的指令.  

ps:分析这个问题的时候,使用了两个反编译工具jad和jd-gui,发现它们对boolean,short,byte,char这些类型处理的时候都是存在问题的.

转载请注明原文地址: https://www.6miu.com/read-4933580.html

最新回复(0)