KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > kawa > lang > SetFieldProc


1 package kawa.lang;
2 import gnu.bytecode.*;
3 import gnu.mapping.*;
4 import gnu.expr.*;
5
6 // Should be called PrimSetField for consistency.
7

8 public class SetFieldProc extends Procedure2 implements Inlineable
9 {
10   ClassType ctype;
11   Field field;
12
13   public SetFieldProc (Class JavaDoc clas, String JavaDoc fname)
14   {
15     this ((ClassType) Type.make(clas), fname);
16   }
17
18   public SetFieldProc (ClassType ctype, String JavaDoc fname)
19   {
20     this.ctype = ctype;
21     this.field = Field.searchField(ctype.getFields(), fname);
22   }
23
24   public SetFieldProc (ClassType ctype, String JavaDoc name, Type ftype, int flags)
25   {
26     this.ctype = ctype;
27     field = ctype.getField(name);
28     if (field == null)
29       field = ctype.addField(name, ftype, flags);
30   }
31
32   public Object JavaDoc apply2 (Object JavaDoc arg1, Object JavaDoc arg2)
33   {
34     try
35       {
36     java.lang.reflect.Field JavaDoc reflectField = field.getReflectField();
37     arg2 = field.getType().coerceFromObject(arg2);
38     reflectField.set(arg1, arg2);
39       }
40     catch (NoSuchFieldException JavaDoc ex)
41       {
42     throw new RuntimeException JavaDoc ("no such field " + field.getSourceName()
43                     + " in " + ctype.getName());
44       }
45     catch (IllegalAccessException JavaDoc ex)
46       {
47     throw new RuntimeException JavaDoc("illegal access for field "
48                    + field.getSourceName());
49       }
50     return Values.empty;
51   }
52
53   public void compile (ApplyExp exp, Compilation comp, Target target)
54   {
55     ClassLoader JavaDoc loader = ctype.getReflectClass().getClassLoader();
56     if (loader instanceof gnu.bytecode.ArrayClassLoader)
57       {
58         ApplyExp.compile(exp, comp, target);
59         return;
60       }
61     Expression[] args = exp.getArgs();
62     args[0].compile(comp, ctype);
63     args[1].compile(comp, field.getType());
64     gnu.bytecode.CodeAttr code = comp.getCode();
65     code.emitPutField(field);
66     comp.compileConstant(Values.empty, target);
67   }
68
69   public gnu.bytecode.Type getReturnType (Expression[] args)
70   {
71     return Type.void_type;
72   }
73 }
74
Popular Tags