Generating byte code from a Java class file


I have been reading through the Java virtual machine specification, which covers all the details needed to implement a JVM. Once thing the specification talks about in detail is Java bytecode, which is the machine independent code that is executed by the virtual machine implementation. At various places in the specification I wondered what the byte code would look like for a chunk of Java code. Fortunately for me, the Java SDK comes with the javap utility, which can be run with the “-c” option to translate a class file into byte code:

$ javap -c -s -verbose MyEnv

{
MyEnv();
Signature: ()V
Code:
Stack=1, Locals=1, Args_size=1
0: aload_0
1: invokespecial #1; //Method java/lang/Object."":()V
4: return
LineNumberTable:
line 3: 0

public static void main(java.lang.String[]);
Signature: ([Ljava/lang/String;)V
Code:
Stack=2, Locals=2, Args_size=1
0: new #2; //class MyEnv
3: dup
4: invokespecial #3; //Method "":()V
7: astore_1
8: aload_1
9: invokespecial #4; //Method allocateObjects:()V
12: return
LineNumberTable:
line 7: 0
line 8: 8
line 9: 12
}

In the output above, you can see the methods and constants the MyEnv class utilizes, and the byte code that makes up the main method in the MyEnv class. Javap is amazingly cool, and I am starting to realize that understanding byte code can a super useful tool for debugging problems.

This article was posted by Matty on 2007-12-16 18:31:00 -0400 -0400