KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > samples > reflect > hello1 > HelloWorldBuilder


1 package samples.reflect.hello1;
2
3 import java.io.FileOutputStream JavaDoc;
4 import java.lang.reflect.Modifier JavaDoc;
5
6 import alt.jiapi.reflect.Instruction;
7 import alt.jiapi.reflect.InstructionFactory;
8 import alt.jiapi.reflect.InstructionList;
9 import alt.jiapi.reflect.JiapiClass;
10 import alt.jiapi.reflect.JiapiMethod;
11 import alt.jiapi.reflect.Loader;
12 import alt.jiapi.reflect.Signature;
13
14 public class HelloWorldBuilder {
15     public static void main(String JavaDoc args[]) throws Exception JavaDoc {
16         new HelloWorldBuilder();
17     }
18
19     public HelloWorldBuilder() throws Exception JavaDoc {
20         // Load the target class:
21
Loader loader = new Loader();
22         JiapiClass clazz = loader.loadClass("samples.reflect.hello1.Test");
23         System.out.println(clazz);
24
25         // Add an empty method for a clazz. The method signature must
26
// match the method from HelloWorld interface, the only difference
27
// is that we want to implement the method now so it can't be abstract.
28
Signature signature = new Signature("void", new String JavaDoc[] {} );
29         JiapiMethod method = clazz.addMethod(Modifier.PUBLIC, "helloWorld",
30                                              signature);
31         
32         // Then create the method body. The body will make a call to
33
// System.out.println and then just return.
34
InstructionList il = method.getInstructionList();
35         InstructionFactory iFactory = method.getInstructionFactory();
36
37         JiapiMethod println = clazz.getDeclaredMethod("println", new String JavaDoc[]
38                                                       {"java.lang.Object"});
39
40 // il.add(iFactory.getField(loader.loadClass("java.lang.System").getField("out")));
41
// JiapiMethod println = loader.loadClass(System.out.getClass().getName()).getMethod("println", new String[] { "java.lang.String" } );
42

43         il.add(iFactory.pushConstant("hello world!"));
44
45         il.add(iFactory.invoke(println));
46         il.add(iFactory.returnMethod(method));
47
48         // Finalize the modified class and dump it to the file:
49

50         clazz.dump(new FileOutputStream JavaDoc("Test.class"));
51     }
52 }
53
Popular Tags