例:
package deep;
public class PostfixIncrementOperator {
public static void main(String[] args) {
int i = 10;
i = i++;
System.out.println(i);
}
}
运行结果:10
首先我们看JLS中对后置加的解释:The result of the postfix increment expression is not a variable, but a value. 即后置加的结果不是一个变量,而是一个值。并且后置加的优先级在赋值之前,所以是先完成的后置加再进行的赋值。
我们先使用javac -g PostfixIncrementOperator.java
编译源码,再使用javap -c -s -l -v PostfixIncrementOperator.class
反汇编此class.。如下:
Classfile /C:/Users/tspoi/workspace/Test/src/deep/PostfixIncrementOperator.class
Last modified 2015-8-7; size 584 bytes
MD5 checksum 69c9ee93f1dbe68468d009ddf8f0a1b1
Compiled from "PostfixIncrementOperator.java"
public class deep.PostfixIncrementOperator
minor version: 0
major version: 52
flags: ACC_PUBLIC, ACC_SUPER
Constant pool:
#1 = Methodref #5.#21 // java/lang/Object."<init>":()V
#2 = Fieldref #22.#23 // java/lang/System.out:Ljava/io/PrintStream;
#3 = Methodref #24.#25 // java/io/PrintStream.println:(I)V
#4 = Class #26 // deep/PostfixIncrementOperator
#5 = Class #27 // java/lang/Object
#6 = Utf8 <init>
#7 = Utf8 ()V
#8 = Utf8 Code
#9 = Utf8 LineNumberTable
#10 = Utf8 LocalVariableTable
#11 = Utf8 this
#12 = Utf8 Ldeep/PostfixIncrementOperator;
#13 = Utf8 main
#14 = Utf8 ([Ljava/lang/String;)V
#15 = Utf8 args
#16 = Utf8 [Ljava/lang/String;
#17 = Utf8 i
#18 = Utf8 I
#19 = Utf8 SourceFile
#20 = Utf8 PostfixIncrementOperator.java
#21 = NameAndType #6:#7 // "<init>":()V
#22 = Class #28 // java/lang/System
#23 = NameAndType #29:#30 // out:Ljava/io/PrintStream;
#24 = Class #31 // java/io/PrintStream
#25 = NameAndType #32:#33 // println:(I)V
#26 = Utf8 deep/PostfixIncrementOperator
#27 = Utf8 java/lang/Object
#28 = Utf8 java/lang/System
#29 = Utf8 out
#30 = Utf8 Ljava/io/PrintStream;
#31 = Utf8 java/io/PrintStream
#32 = Utf8 println
#33 = Utf8 (I)V
{
public deep.PostfixIncrementOperator();
descriptor: ()V
flags: ACC_PUBLIC
Code:
stack=1, locals=1, args_size=1
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: return
LineNumberTable:
line 3: 0
LocalVariableTable:
Start Length Slot Name Signature
0 5 0 this Ldeep/PostfixIncrementOperator;
public static void main(java.lang.String[]);
descriptor: ([Ljava/lang/String;)V
flags: ACC_PUBLIC, ACC_STATIC
Code:
stack=2, locals=2, args_size=1
0: bipush 10
2: istore_1
3: iload_1
4: iinc 1, 1
7: istore_1
8: getstatic #2 // Field java/lang/System.out:Ljava/io/PrintStream;
11: iload_1
12: invokevirtual #3 // Method java/io/PrintStream.println:(I)V
15: return
LineNumberTable:
line 5: 0
line 6: 3
line 7: 8
line 8: 15
LocalVariableTable:
Start Length Slot Name Signature
0 16 0 args [Ljava/lang/String;
3 13 1 i I
}
我们主要看关键部分:
0: bipush 10 //常数10入栈
2: istore_1 //常数值出栈,i入栈
//至此完成i=10;
3: iload_1 //装载变量i,10入栈
//这是特殊的一步,这步将i值先行保存,以备赋值使用
4: iinc 1, 1 //变量值增加,栈内值不变
7: istore_1 //i赋值,还是赋的10,因为栈内值未改变
So…