KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > hworld


1 import jas.*;
2 import java.io.*;
3
4 //
5
// This is program that makes calls into the jas package
6
// to generate a class that prints a string afew times.
7
//
8

9 class hworld implements RuntimeConstants
10 {
11   public static void main(String JavaDoc argv[])
12     throws jasError, IOException
13   {
14
15                                 // class hierarchy
16
ClassEnv nclass = new ClassEnv();
17     nclass.setClass(new ClassCP("out"));
18     nclass.setSuperClass(new ClassCP("java/lang/Object"));
19     nclass.setClassAccess((short)ACC_PUBLIC);
20
21                                 // Initialization code
22

23     CodeAttr init = new CodeAttr();
24     init.addInsn(new Insn(opc_aload_0));
25     init.addInsn(new Insn(opc_invokenonvirtual,
26                           new MethodCP("java/lang/Object", "<init>", "()V")));
27     init.addInsn(new Insn(opc_return));
28
29
30                                 // Actual code to print string
31
CodeAttr doit = new CodeAttr();
32
33                                 // store refs in local variables
34
doit.addInsn(new Insn(opc_getstatic,
35                           new FieldCP("java/lang/System",
36                                       "out",
37                                       "Ljava/io/PrintStream;")));
38     doit.addInsn(new Insn(opc_astore_1));
39     doit.addInsn(new Insn(opc_ldc,
40                           new StringCP("Hello World")));
41     doit.addInsn(new Insn(opc_astore_2));
42
43                                 // Loop index in var reg 3
44
doit.addInsn(new Insn(opc_bipush, 5));
45     doit.addInsn(new Insn(opc_istore_3));
46
47                                 // Start the loop
48
Label loop = new Label("loop");
49     doit.addInsn(loop);
50     doit.addInsn(new Insn(opc_aload_1));
51     doit.addInsn(new Insn(opc_aload_2));
52     doit.addInsn(new Insn(opc_invokevirtual,
53                           new MethodCP("java/io/PrintStream",
54                                        "println",
55                                        "(Ljava/lang/String;)V")));
56     doit.addInsn(new IincInsn(3, -1));
57     doit.addInsn(new Insn(opc_iload_3));
58     doit.addInsn(new Insn(opc_ifne, loop));
59     doit.addInsn(new Insn(opc_return));
60
61                                 // set the right sizes for code
62
doit.setStackSize((short)3); doit.setVarSize((short)4);
63
64                                 // Add the init code to the class.
65
nclass.addMethod((short)ACC_PUBLIC, "<init>", "()V", init, null);
66
67                                 // Add the printing code
68
nclass.addMethod((short)(ACC_PUBLIC|ACC_STATIC), "main",
69                      "([Ljava/lang/String;)V", doit, null);
70
71                                 // write it all out
72
nclass.write(new DataOutputStream
73                  (new FileOutputStream("out.class")));
74   }
75 }
76
77     
78
Popular Tags