b2d25bc9a2e5de5dae134c28763ea9aa42fd1c55
[org.ibex.classgen.git] / src / org / ibex / classgen / FieldGen.java
1 package org.ibex.classgen;
2
3 import java.io.*;
4
5 public class FieldGen implements CGConst {
6     private final CPGen cp;
7     private final String name;
8     private final Type type;
9     private final int flags;
10     private final ClassGen.AttrGen attrs;
11     
12     private Object constantValue;
13     
14     FieldGen(ClassGen owner, String name,Type type, int flags) {
15         if((flags & ~(ACC_PUBLIC|ACC_PRIVATE|ACC_PROTECTED|ACC_VOLATILE|ACC_TRANSIENT|ACC_STATIC|ACC_FINAL)) != 0)
16             throw new IllegalArgumentException("invalid flags");
17         this.cp = owner.cp;
18         this.name = name;
19         this.type = type;
20         this.flags = flags;
21         this.attrs = new ClassGen.AttrGen(cp);
22         
23         cp.addUtf8(name);
24         cp.addUtf8(type.getDescriptor());
25     }
26     
27     /** Sets the ContantValue attribute for this field. 
28         @param val The value to set this field to. Must be an Integer, Long, Float, Double, or String */
29     public void setConstantValue(Object val) {
30         if((flags & ACC_STATIC) == 0) throw new IllegalStateException("field does not have the ACC_STATIC bit set");
31         constantValue = val;
32     }
33     
34     void finish() {
35         if(constantValue != null && !attrs.contains("ConstantValue"))
36             attrs.add("ConstantValue",cp.add(constantValue));
37     }
38     
39     void dump(DataOutput o) throws IOException {
40         o.writeShort(flags);
41         o.writeShort(cp.getUtf8Index(name));
42         o.writeShort(cp.getUtf8Index(type.getDescriptor()));
43         o.writeShort(attrs.size());
44         attrs.dump(o);
45     }
46 }