f29e1da48c2124af41a9cf6826ef709028f973c7
[org.ibex.classgen.git] / src / org / ibex / classgen / FieldGen.java
1 package org.ibex.classgen;
2
3 import java.io.*;
4
5 /** Class representing a field in a generated classfile
6     @see ClassFile#addField */
7 public class FieldGen implements CGConst {
8     private final String name;
9     private final Type type;
10     private final int flags;
11     private final ClassFile.AttrGen attrs;
12
13     StringBuffer debugToString(StringBuffer sb) {
14         sb.append(ClassFile.flagsToString(flags,false));
15         sb.append(type.debugToString());
16         sb.append(" ");
17         sb.append(name);
18         if(attrs.contains("ConstantValue"))
19             sb.append(" = \"").append(attrs.get("ConstantValue")).append("\"");
20         sb.append(";");
21         return sb;
22     }
23     
24     FieldGen(DataInput in, ConstantPool cp) throws IOException {
25         flags = in.readShort();
26         if((flags & ~VALID_FIELD_FLAGS) != 0)
27             throw new ClassFile.ClassReadExn("invalid flags");        
28         name = cp.getUtf8KeyByIndex(in.readShort());
29         type = Type.instance(cp.getUtf8KeyByIndex(in.readShort()));
30         attrs = new ClassFile.AttrGen(in,cp);
31     }
32
33     FieldGen(ClassFile owner, String name, Type type, int flags) {
34         if((flags & ~VALID_FIELD_FLAGS) != 0)
35             throw new IllegalArgumentException("invalid flags");
36         this.name = name;
37         this.type = type;
38         this.flags = flags;
39         this.attrs = new ClassFile.AttrGen();        
40    }
41     
42     /** Sets the ContantValue attribute for this field. 
43         @param val The value to set this field to. Must be an Integer, Long, Float, Double, or String */
44     public void setConstantValue(Object val) {
45         if((flags & STATIC) == 0) throw new IllegalStateException("field does not have the STATIC bit set");
46         attrs.put("ConstantValue",val);
47     }
48     
49     void finish(ConstantPool cp) {
50         cp.addUtf8(name);
51         cp.addUtf8(type.getDescriptor());
52         
53         attrs.finish(cp);
54     }
55     
56     void dump(DataOutput o, ConstantPool cp) throws IOException {
57         o.writeShort(flags);
58         o.writeShort(cp.getUtf8Index(name));
59         o.writeShort(cp.getUtf8Index(type.getDescriptor()));
60         attrs.dump(o,cp);
61     }
62 }