实践中的 Java 字节码
public class Autoboxing
{
public static void main(String[] args)
{
int x = 5;
java.util.ArrayList al = new java.util.ArrayList();
al.add(x);
}
}
0: iconst_5
1: istore_1
2: new #2; //class java/util/ArrayList
5: dup
6: invokespecial #3; //Method java/util/ArrayList."<init>":()V
9: astore_2
10: aload_2
11: iload_1
12: invokestatic #4; //Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
15: invokevirtual #5; //Method java/util/ArrayList.add:(Ljava/lang/Object;)Z
18: pop
19: return
class Outer
{
private int data = 12;
public Inner getInner()
{
return new Inner();
}
public class Inner
{
public int getData()
{
return data;
}
}
}
public class NestedFun
{
public static void main(String[] args)
{
Outer o = new Outer();
Outer.Inner i = o.getInner();
System.out.println(i.getData());
// prints 12; how?
}
}
public static void main(java.lang.String[]);
Code:
Stack=2, Locals=3, Args_size=1
0: new #2; //class Outer
3: dup
4: invokespecial #3; //Method Outer."<init>":()V
7: astore_1
8: aload_1
9: invokevirtual #4; //Method Outer.getInner:()LOuter$Inner;
12: astore_2
13: getstatic #5; //Field java/lang/System.out:Ljava/io/PrintStream;
16: aload_2
17: invokevirtual #6; //Method Outer$Inner.getData:()I
20: invokevirtual #7; //Method java/io/PrintStream.println:(I)V
23: return
public class Outer$Inner extends java.lang.Object
SourceFile: "NestedFun.java"
InnerClass:
public #21= #4 of #18; //Inner=class Outer$Inner of class Outer
minor version: 0
major version: 50
Constant pool: (snipped)
{
final Outer this$0;
public Outer$Inner(Outer);
Code:
Stack=2, Locals=2, Args_size=2
0: aload_0
1: aload_1
2: putfield #1; //Field this$0:LOuter;
5: aload_0
6: invokespecial #2; //Method java/lang/Object."<init>":()V
9: return
public int getData();
Code:
Stack=1, Locals=1, Args_size=1
0: aload_0
1: getfield #1; //Field this$0:LOuter;
4: invokestatic #3; //Method Outer.access$000:(LOuter;)I
7: ireturn
}
class Outer extends java.lang.Object{
private int data;
Outer();
Code:
0: aload_0
1: invokespecial #2; //Method java/lang/Object."<init>":()V
4: aload_0
5: bipush 12
7: putfield #1; //Field data:I
10: return
public Outer$Inner getInner();
Code:
0: new #3; //class Outer$Inner
3: dup
4: aload_0
5: invokespecial #4; //Method Outer$Inner."<init>":(LOuter;)V
8: areturn
static int access$000(Outer);
Code:
0: aload_0
1: getfield #1; //Field data:I
4: ireturn
}
也许,最重要的拆解字节码的工具还是 javap 。
The Java Virtual Machine Specification(2nd Edition) JVM规范(第二版)