7f5242c87f08c6637ee0f31793c3aa8ed19e7c2f
[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 extends Type.Class.Field.Body {
8     private final ClassFile.AttrGen attrs;
9
10     StringBuffer debugToString(StringBuffer sb) {
11         sb.append(ClassFile.flagsToString(flags, false));
12         sb.append(getField().getType().debugToString());
13         sb.append(" ");
14         sb.append(getField().getName());
15         if(attrs.contains("ConstantValue"))
16             sb.append(" = \"").append(attrs.get("ConstantValue")).append("\"");
17         sb.append(";");
18         return sb;
19     }
20     
21     FieldGen(ClassFile cf, DataInput in, ConstantPool cp) throws IOException {
22         this(in.readShort(),
23              cf.getType().field(cp.getUtf8KeyByIndex(in.readShort()),
24                                 Type.fromDescriptor(cp.getUtf8KeyByIndex(in.readShort()))));
25     }
26
27     private FieldGen(int flags, Type.Class.Field field) { this(field, flags); }
28     FieldGen(Type.Class.Field field, int flags) { this(field, flags, new ClassFile.AttrGen()); }
29     FieldGen(Type.Class.Field field, int flags, ClassFile.AttrGen attrs) {
30         field.super(flags);
31         this.attrs = attrs;
32    }
33     
34     /** Sets the ContantValue attribute for this field. 
35         @param val The value to set this field to. Must be an Integer, Long, Float, Double, or String */
36     public void setConstantValue(Object val) {
37         if (!isStatic()) throw new IllegalStateException("field does not have the STATIC bit set");
38         attrs.put("ConstantValue",val);
39     }
40     
41     void finish(ConstantPool cp) {
42         cp.addUtf8(getField().getName());
43         cp.addUtf8(getField().getType().getDescriptor());
44         
45         attrs.finish(cp);
46     }
47     
48     void dump(DataOutput o, ConstantPool cp) throws IOException {
49         o.writeShort(getFlags());
50         o.writeShort(cp.getUtf8Index(getField().getName()));
51         o.writeShort(cp.getUtf8Index(getField().getType().getDescriptor()));
52         attrs.dump(o,cp);
53     }
54 }