KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > alt > jiapi > reflect > ClassBuilder


1 package alt.jiapi.reflect;
2
3 import java.util.Iterator JavaDoc;
4 import java.util.List JavaDoc;
5 import java.util.LinkedList JavaDoc;
6
7 import alt.jiapi.file.ClassFile;
8 import alt.jiapi.file.ConstantPool;
9 import alt.jiapi.file.Field;
10 import alt.jiapi.file.Method;
11 import alt.jiapi.file.SyntheticAttribute;
12 import alt.jiapi.file.CodeAttribute;
13
14 /**
15  * Class ClassBuilder.
16  *
17  * @author Mika Riekkinen
18  */

19 class ClassBuilder {
20     private ClassFile clazz;
21
22     ClassBuilder(ClassFile clazz) {
23         this.clazz = clazz;
24     }
25
26     JiapiField addField(short modifiers, String JavaDoc type, String JavaDoc name) throws FieldExistsException {
27         ConstantPool cp = clazz.getConstantPool();
28
29         // Check, that the field don't exist
30
List JavaDoc fields = clazz.getFields();
31         Iterator JavaDoc i = fields.iterator();
32         while(i.hasNext()) {
33             Field field = (Field)i.next();
34             if (field.getName().equals(name)) {
35                 throw new FieldExistsException(new JiapiField(field));
36             }
37         }
38
39         // Add Synthetic attribute for the field
40
List JavaDoc attrs = new LinkedList JavaDoc();
41         attrs.add(new SyntheticAttribute(cp));
42
43         // Create field, and add it to ClassFile
44
Field f = new Field(cp, modifiers, name,
45                             TypeHelper.typeToDescriptor(type), attrs);
46         fields.add(f);
47
48         return new JiapiField(f);
49     }
50
51
52     JiapiMethod addMethod(short modifiers, String JavaDoc name, Signature signature) throws MethodExistsException {
53         ConstantPool cp = clazz.getConstantPool();
54
55
56         // Add Synthetic attribute for the field
57
List JavaDoc attrs = new LinkedList JavaDoc();
58         attrs.add(new SyntheticAttribute(cp));
59
60         short maxStack = 0;
61         int maxLocals = signature.getParameters().length + 1;
62
63         attrs.add(new CodeAttribute(cp, maxStack, (short)maxLocals));
64
65         // Create field, and add it to ClassFile
66
Method m = new Method(cp, modifiers, name, signature.getDescriptor(),
67                               attrs);
68
69         clazz.getMethods().add(m);
70
71         return new JiapiMethod(m);
72     }
73
74
75     ClassFile getClassFile() {
76         return clazz;
77     }
78 }
79
Popular Tags