KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > org > apache > bcel > internal > generic > FieldGen


1 package com.sun.org.apache.bcel.internal.generic;
2
3 /* ====================================================================
4  * The Apache Software License, Version 1.1
5  *
6  * Copyright (c) 2001 The Apache Software Foundation. All rights
7  * reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  *
13  * 1. Redistributions of source code must retain the above copyright
14  * notice, this list of conditions and the following disclaimer.
15  *
16  * 2. Redistributions in binary form must reproduce the above copyright
17  * notice, this list of conditions and the following disclaimer in
18  * the documentation and/or other materials provided with the
19  * distribution.
20  *
21  * 3. The end-user documentation included with the redistribution,
22  * if any, must include the following acknowledgment:
23  * "This product includes software developed by the
24  * Apache Software Foundation (http://www.apache.org/)."
25  * Alternately, this acknowledgment may appear in the software itself,
26  * if and wherever such third-party acknowledgments normally appear.
27  *
28  * 4. The names "Apache" and "Apache Software Foundation" and
29  * "Apache BCEL" must not be used to endorse or promote products
30  * derived from this software without prior written permission. For
31  * written permission, please contact apache@apache.org.
32  *
33  * 5. Products derived from this software may not be called "Apache",
34  * "Apache BCEL", nor may "Apache" appear in their name, without
35  * prior written permission of the Apache Software Foundation.
36  *
37  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
38  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
39  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
40  * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
41  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
42  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
43  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
44  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
45  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
46  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
47  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
48  * SUCH DAMAGE.
49  * ====================================================================
50  *
51  * This software consists of voluntary contributions made by many
52  * individuals on behalf of the Apache Software Foundation. For more
53  * information on the Apache Software Foundation, please see
54  * <http://www.apache.org/>.
55  */

56
57 import com.sun.org.apache.bcel.internal.Constants;
58 import com.sun.org.apache.bcel.internal.classfile.*;
59 import java.util.ArrayList JavaDoc;
60 import java.util.Iterator JavaDoc;
61
62 /**
63  * Template class for building up a field. The only extraordinary thing
64  * one can do is to add a constant value attribute to a field (which must of
65  * course be compatible with to the declared type).
66  *
67  * @version $Id: FieldGen.java,v 1.1.1.1 2001/10/29 20:00:12 jvanzyl Exp $
68  * @author <A HREF="mailto:markus.dahm@berlin.de">M. Dahm</A>
69  * @see Field
70  */

71 public class FieldGen extends FieldGenOrMethodGen {
72   private Object JavaDoc value = null;
73
74   /**
75    * Declare a field. If it is static (isStatic() == true) and has a
76    * basic type like int or String it may have an initial value
77    * associated with it as defined by setInitValue().
78    *
79    * @param access_flags access qualifiers
80    * @param type field type
81    * @param name field name
82    * @param cp constant pool
83    */

84   public FieldGen(int access_flags, Type type, String JavaDoc name, ConstantPoolGen cp) {
85     setAccessFlags(access_flags);
86     setType(type);
87     setName(name);
88     setConstantPool(cp);
89   }
90
91   /**
92    * Instantiate from existing field.
93    *
94    * @param field Field object
95    * @param cp constant pool (must contain the same entries as the field's constant pool)
96    */

97   public FieldGen(Field field, ConstantPoolGen cp) {
98     this(field.getAccessFlags(), Type.getType(field.getSignature()), field.getName(), cp);
99
100     Attribute[] attrs = field.getAttributes();
101
102     for(int i=0; i < attrs.length; i++) {
103       if(attrs[i] instanceof ConstantValue)
104     setValue(((ConstantValue)attrs[i]).getConstantValueIndex());
105       else
106     addAttribute(attrs[i]);
107     }
108   }
109
110   private void setValue(int index) {
111     ConstantPool cp = this.cp.getConstantPool();
112     Constant c = cp.getConstant(index);
113     value = ((ConstantObject)c).getConstantValue(cp);
114   }
115
116   /**
117    * Set (optional) initial value of field, otherwise it will be set to null/0/false
118    * by the JVM automatically.
119    */

120   public void setInitValue(String JavaDoc str) {
121     checkType(new ObjectType("java.lang.String"));
122
123     if(str != null)
124       value = str;
125   }
126
127   public void setInitValue(long l) {
128     checkType(Type.LONG);
129
130     if(l != 0L)
131       value = new Long JavaDoc(l);
132   }
133
134   public void setInitValue(int i) {
135     checkType(Type.INT);
136
137     if(i != 0)
138       value = new Integer JavaDoc(i);
139   }
140
141   public void setInitValue(short s) {
142     checkType(Type.SHORT);
143
144     if(s != 0)
145       value = new Integer JavaDoc(s);
146   }
147
148   public void setInitValue(char c) {
149     checkType(Type.CHAR);
150
151     if(c != 0)
152       value = new Integer JavaDoc(c);
153   }
154
155   public void setInitValue(byte b) {
156     checkType(Type.BYTE);
157
158     if(b != 0)
159       value = new Integer JavaDoc(b);
160   }
161
162   public void setInitValue(boolean b) {
163     checkType(Type.BOOLEAN);
164
165     if(b)
166       value = new Integer JavaDoc(1);
167   }
168
169   public void setInitValue(float f) {
170     checkType(Type.FLOAT);
171
172     if(f != 0.0)
173       value = new Float JavaDoc(f);
174   }
175
176   public void setInitValue(double d) {
177     checkType(Type.DOUBLE);
178
179     if(d != 0.0)
180       value = new Double JavaDoc(d);
181   }
182
183   /** Remove any initial value.
184    */

185   public void cancelInitValue() {
186     value = null;
187   }
188
189   private void checkType(Type atype) {
190     if(type == null)
191       throw new ClassGenException("You haven't defined the type of the field yet");
192     
193     if(!isFinal())
194       throw new ClassGenException("Only final fields may have an initial value!");
195
196     if(!type.equals(atype))
197       throw new ClassGenException("Types are not compatible: " + type + " vs. " + atype);
198   }
199
200   /**
201    * Get field object after having set up all necessary values.
202    */

203   public Field getField() {
204     String JavaDoc signature = getSignature();
205     int name_index = cp.addUtf8(name);
206     int signature_index = cp.addUtf8(signature);
207
208     if(value != null) {
209       checkType(type);
210       int index = addConstant();
211       addAttribute(new ConstantValue(cp.addUtf8("ConstantValue"),
212                      2, index, cp.getConstantPool()));
213     }
214
215     return new Field(access_flags, name_index, signature_index, getAttributes(),
216              cp.getConstantPool());
217   }
218
219   private int addConstant() {
220     switch(type.getType()) {
221     case Constants.T_INT: case Constants.T_CHAR: case Constants.T_BYTE:
222     case Constants.T_BOOLEAN: case Constants.T_SHORT:
223       return cp.addInteger(((Integer JavaDoc)value).intValue());
224       
225     case Constants.T_FLOAT:
226       return cp.addFloat(((Float JavaDoc)value).floatValue());
227
228     case Constants.T_DOUBLE:
229       return cp.addDouble(((Double JavaDoc)value).doubleValue());
230
231     case Constants.T_LONG:
232       return cp.addLong(((Long JavaDoc)value).longValue());
233
234     case Constants.T_REFERENCE:
235       return cp.addString(((String JavaDoc)value));
236
237     default:
238       throw new RuntimeException JavaDoc("Oops: Unhandled : " + type.getType());
239     }
240   }
241
242   public String JavaDoc getSignature() { return type.getSignature(); }
243
244   private ArrayList JavaDoc observers;
245
246   /** Add observer for this object.
247    */

248   public void addObserver(FieldObserver o) {
249     if(observers == null)
250       observers = new ArrayList JavaDoc();
251
252     observers.add(o);
253   }
254
255   /** Remove observer for this object.
256    */

257   public void removeObserver(FieldObserver o) {
258     if(observers != null)
259       observers.remove(o);
260   }
261
262   /** Call notify() method on all observers. This method is not called
263    * automatically whenever the state has changed, but has to be
264    * called by the user after he has finished editing the object.
265    */

266   public void update() {
267     if(observers != null)
268       for(Iterator JavaDoc e = observers.iterator(); e.hasNext(); )
269     ((FieldObserver)e.next()).notify(this);
270   }
271
272   public String JavaDoc getInitValue() {
273     if(value != null) {
274       return value.toString();
275     } else
276       return null;
277   }
278
279   /**
280    * Return string representation close to declaration format,
281    * `public static final short MAX = 100', e.g..
282    *
283    * @return String representation of field
284    */

285   public final String JavaDoc toString() {
286     String JavaDoc name, signature, access; // Short cuts to constant pool
287

288     access = Utility.accessToString(access_flags);
289     access = access.equals("")? "" : (access + " ");
290     signature = type.toString();
291     name = getName();
292
293     StringBuffer JavaDoc buf = new StringBuffer JavaDoc(access + signature + " " + name);
294     String JavaDoc value = getInitValue();
295
296     if(value != null)
297       buf.append(" = " + value);
298
299     return buf.toString();
300   }
301
302   /** @return deep copy of this field
303    */

304   public FieldGen copy(ConstantPoolGen cp) {
305     FieldGen fg = (FieldGen)clone();
306
307     fg.setConstantPool(cp);
308     return fg;
309   }
310 }
311
Popular Tags