aab5586c11e185bdf456fb3e380c5846f3628edb
[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 ClassGen#addField */
7 public class FieldGen implements CGConst {
8     private final CPGen cp;
9     private final String name;
10     private final Type type;
11     private final int flags;
12     private final ClassGen.AttrGen attrs;
13     
14     private Object constantValue;
15
16     public String toString() { StringBuffer sb = new StringBuffer(); toString(sb); return sb.toString(); }
17     public void   toString(StringBuffer sb) {
18         sb.append(ClassGen.flagsToString(flags));
19         sb.append(type.humanReadable());
20         sb.append(" ");
21         sb.append(name);
22         sb.append(";");
23         // FIXME: attrs
24     }
25     
26     FieldGen(CPGen cp, DataInput in) throws IOException {
27         this.cp = cp;
28         flags = in.readShort();
29         name = cp.getUtf8ByIndex(in.readShort());
30         type = cp.getType(in.readShort());
31         attrs = new ClassGen.AttrGen(cp, in);
32     }
33
34     FieldGen(ClassGen owner, String name, Type type, int flags) {
35         if((flags & ~(ACC_PUBLIC|ACC_PRIVATE|ACC_PROTECTED|ACC_VOLATILE|ACC_TRANSIENT|ACC_STATIC|ACC_FINAL)) != 0)
36             throw new IllegalArgumentException("invalid flags");
37         this.cp = owner.cp;
38         this.name = name;
39         this.type = type;
40         this.flags = flags;
41         this.attrs = new ClassGen.AttrGen(cp);
42         
43         cp.addUtf8(name);
44         cp.addUtf8(type.getDescriptor());
45     }
46     
47     /** Sets the ContantValue attribute for this field. 
48         @param val The value to set this field to. Must be an Integer, Long, Float, Double, or String */
49     public void setConstantValue(Object val) {
50         if((flags & ACC_STATIC) == 0) throw new IllegalStateException("field does not have the ACC_STATIC bit set");
51         constantValue = val;
52     }
53     
54     void finish() {
55         if(constantValue != null && !attrs.contains("ConstantValue"))
56             attrs.add("ConstantValue", cp.add(constantValue));
57     }
58     
59     void dump(DataOutput o) throws IOException {
60         o.writeShort(flags);
61         o.writeShort(cp.getUtf8Index(name));
62         o.writeShort(cp.getUtf8Index(type.getDescriptor()));
63         o.writeShort(attrs.size());
64         attrs.dump(o);
65     }
66 }