1 package kawa.lang; 2 import gnu.bytecode.*; 3 import gnu.mapping.*; 4 import gnu.lists.*; 5 6 public class RecordConstructor extends ProcedureN 7 { 8 ClassType type; 9 Field[] fields; 10 11 public RecordConstructor (ClassType type, Field[] fields) 12 { 13 this.type = type; 14 this.fields = fields; 15 } 16 17 public RecordConstructor (Class clas, Field[] fields) 18 { 19 this((ClassType) Type.make(clas), fields); 20 } 21 22 public RecordConstructor (Class clas) 23 { 24 init((ClassType) Type.make(clas)); 25 } 26 27 public RecordConstructor (ClassType type) 28 { 29 init(type); 30 } 31 32 private void init(ClassType type) 33 { 34 this.type = type; 35 Field list = type.getFields(); 36 int count = 0; 37 for (Field fld = list; fld != null; fld = fld.getNext()) 38 { 39 if ((fld.getModifiers() & (Access.PUBLIC|Access.STATIC)) 40 == Access.PUBLIC) 41 count++; 42 } 43 fields = new Field[count]; 44 int i = 0; 45 for (Field fld = list; fld != null; fld = fld.getNext()) 46 { 47 if ((fld.getModifiers() & (Access.PUBLIC|Access.STATIC)) 48 == Access.PUBLIC) 49 fields[i++] = fld; 50 } 51 } 52 53 public RecordConstructor (Class clas, Object fieldsList) 54 { 55 this((ClassType) Type.make(clas), fieldsList); 56 } 57 58 public RecordConstructor (ClassType type, Object fieldsList) 59 { 60 this.type = type; 61 if (fieldsList == null) 62 init(type); 63 else 64 { 65 int nfields = LList.listLength(fieldsList, false); 66 this.fields = new Field[nfields]; 67 Field list = type.getFields(); 68 for (int i = 0; i < nfields; i++) 69 { 70 Pair pair = (Pair) fieldsList; 71 String fname = pair.car.toString(); 72 for (Field fld = list; ; fld = fld.getNext()) 73 { 74 if (fld == null) 75 throw new RuntimeException ("no such field "+fname+" in "+type.getName()); 76 if (fld.getSourceName() == fname) 77 { 78 this.fields[i] = fld; 79 break; 80 } 81 } 82 fieldsList = pair.cdr; 83 } 84 } 85 } 86 87 public int numArgs() 88 { 89 int nargs = fields.length; 90 return (nargs<<12)|nargs; 91 } 92 93 public String getName() 94 { 95 return type.getName()+" constructor"; 96 } 97 98 public Object applyN (Object [] args) 99 { 100 Object obj; 101 try 102 { 103 obj = type.getReflectClass().newInstance(); 104 } 105 catch (InstantiationException ex) 106 { 107 throw new GenericError (ex.toString()); 108 } 109 catch (IllegalAccessException ex) 110 { 111 throw new GenericError (ex.toString()); 112 } 113 if (args.length != fields.length) 114 throw new WrongArguments(this, args.length); 115 for (int i = 0; i < args.length; i++) 116 { 117 Field fld = fields[i]; 118 try 119 { 120 fld.getReflectField().set(obj, args[i]); 121 } 122 catch (Exception ex) 123 { 124 throw new WrappedException("illegal access for field "+fld.getName(), ex); 125 } 126 } 127 return obj; 128 } 129 } 130 | Popular Tags |