Java Reference
In-Depth Information
JMethodDeclaration
s and
JConstructorDeclaration
s add themselves, using
addMethod
()
, and then delegate their code generation to their bodies. It is not rocket science.
The code for
JMethodDeclaration.codegen()
illustrates what these
codegen()
meth-
ods look like:
publicvoidcodegen(CLEmitteroutput){
output.addMethod(mods,name,descriptor,null,false);
if(body!=null){
body.codegen(output);
}
//AddimplicitRETURN
if(returnType==Type.VOID){
output.addNoArgInstruction(RETURN);
}
}
In general, we generate only the class headers, members, and their instructions and
operands.
CLEmitter
takes care of the rest. For example, here is the result of executing
>javapHelloWorld
where
javap
is a Java tool that disassembles
HelloWorld.class
:
publicclassHelloWorldextendsjava.lang.Object
{
publicHelloWorld();
Code:
Stack=1,Locals=1,Args_size=1
0:aload_0
1:invokespecial #8;//Methodjava/lang/Object."<init>":()V
4:return
publicstaticvoidmain(java.lang.String[]);
Code:
Stack=2,Locals=1,Args_size=1
0:getstatic #17;//Fieldjava/lang/System.out:
//Ljava/io/PrintStream;
3:ldc #19;//StringHello,World!
5:invokevirtual #25;//Methodjava/io/PrintStream.println:
//(Ljava/lang/String;)V
8:return
}
We have shown only the instructions; tables such as the constant table have been left
out of our illustration.
In general,
CLEmitter
does the following for us:
Builds the constant table and generates references that the JVM can use to reference
names and constants; one need only generate the instructions and their operands,
using names and literals.
Computes branch offsets and addresses; the user can use mnemonic labels.
Computes the argument and local variable counts and the stack space a method
requires to do computation.
Constructs the complete class file.
The
CLEmitter
is discussed in more detail in Appendix D. JVM code generation is
discussed more fully in Chapter 5.
Search WWH ::
Custom Search