Java Reference
In-Depth Information
constructor
<init>
,
<init>
with descriptor
()V
, of
Square
's super class
java/lang/Object
,
on the single argument
this
. After invoking the super constructor, the constructor simply
returns, obeying the
return
instruction at location 4.
The second, explicit method
square()
is even simpler. The stack frame information,
Stack=2,Locals=2,Args_size=2
says we need two locations for computation (the two operands to the multiplication op-
eration), two local variables allocated (for the implicit parameter
this
, and the explicit
parameter
x
), and that there will be two actual arguments on the stack:
this
and the
argument for
x
. The code consists of four one-byte instructions:
0:iload_1
1:iload_1
2:imul
3:ireturn
The instruction at location 0 loads the value for
x
onto the stack; the instruction at location
1 does the same. The instruction at location 2 pops those two values off the stack and
performs an integer multiplication on them, leaving its result on the stack. The instruction
at location 3 returns the integer (
x*x
) on the stack as the result of the method invocation.
Of course, to emit these instructions, we first create a
CLEmitter
instance, which is an
abstraction of the class file we wish to build, and then call upon
CLEmitter
's methods for
generating the necessary headers and instructions.
For example, to generate the class header,
publicclassSquareextendsjava.lang.Object
one would invoke the
addClass()
method on
output
, an instance of
CLEmitter
:
output.addClass(mods,"Square","java/lang/Object",false);
where
The
mods
denotes an
ArrayList
containing the single string \public",
Square
is the class name,
java/lang/Object
is the internal form for the fully qualified super class, and
false
indicates that the class is not synthetic.
As a simpler example, the one-byte, no-argument instruction
aload_1
may be generated
by
output.addNoArgInstruction(ALOAD_1);
To fully understand
CLEmitter
and all of its methods for generating code, one should
read through the
CLEmitter.java
source file, which is distributed as part of the j-- compiler.
One must sometimes be careful to pay attention to what the
CLEmitter
is expecting. For
example, sometimes a method requires a fully qualified name in Java form such as
java.
lang.Object
; other times an internal form is required, that is,
java/lang/Object
.
For another, more involved example of code generation, we revisit the
Factorial
class
from Chapters 2 and 3. Recall the source code:
packagepass;
importjava.lang.System;
Search WWH ::
Custom Search