KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > org > apache > bcel > internal > classfile > ConstantPool


1 package com.sun.org.apache.bcel.internal.classfile;
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 java.io.*;
59
60 /**
61  * This class represents the constant pool, i.e., a table of constants.
62  * It may contain null references, due to the JVM specification that skips
63  * an entry after an 8-byte constant (double, long) entry.
64  *
65  * @version $Id: ConstantPool.java,v 1.1.1.1 2001/10/29 19:59:59 jvanzyl Exp $
66  * @see Constant
67  * @author <A HREF="mailto:markus.dahm@berlin.de">M. Dahm</A>
68  */

69 public class ConstantPool implements Cloneable JavaDoc, Node {
70   private int constant_pool_count;
71   private Constant[] constant_pool;
72
73   /**
74    * @param constant_pool Array of constants
75    */

76   public ConstantPool(Constant[] constant_pool)
77   {
78     setConstantPool(constant_pool);
79   }
80
81   /**
82    * Read constants from given file stream.
83    *
84    * @param file Input stream
85    * @throw IOException
86    * @throw ClassFormatError
87    */

88   ConstantPool(DataInputStream file) throws IOException, ClassFormatError JavaDoc
89   {
90     byte tag;
91
92     constant_pool_count = file.readUnsignedShort();
93     constant_pool = new Constant[constant_pool_count];
94
95     /* constant_pool[0] is unused by the compiler and may be used freely
96      * by the implementation.
97      */

98     for(int i=1; i < constant_pool_count; i++) {
99       constant_pool[i] = Constant.readConstant(file);
100       
101       /* Quote from the JVM specification:
102        * "All eight byte constants take up two spots in the constant pool.
103        * If this is the n'th byte in the constant pool, then the next item
104        * will be numbered n+2"
105        *
106        * Thus we have to increment the index counter.
107        */

108       tag = constant_pool[i].getTag();
109       if((tag == Constants.CONSTANT_Double) || (tag == Constants.CONSTANT_Long))
110     i++;
111     }
112   }
113
114   /**
115    * Called by objects that are traversing the nodes of the tree implicitely
116    * defined by the contents of a Java class. I.e., the hierarchy of methods,
117    * fields, attributes, etc. spawns a tree of objects.
118    *
119    * @param v Visitor object
120    */

121   public void accept(Visitor v) {
122     v.visitConstantPool(this);
123   }
124
125   /**
126    * Resolve constant to a string representation.
127    *
128    * @param constant Constant to be printed
129    * @return String representation
130    */

131   public String JavaDoc constantToString(Constant c)
132        throws ClassFormatError JavaDoc
133   {
134     String JavaDoc str;
135     int i;
136     byte tag = c.getTag();
137
138     switch(tag) {
139     case Constants.CONSTANT_Class:
140       i = ((ConstantClass)c).getNameIndex();
141       c = getConstant(i, Constants.CONSTANT_Utf8);
142       str = Utility.compactClassName(((ConstantUtf8)c).getBytes(), false);
143       break;
144
145     case Constants.CONSTANT_String:
146       i = ((ConstantString)c).getStringIndex();
147       c = getConstant(i, Constants.CONSTANT_Utf8);
148       str = "\"" + escape(((ConstantUtf8)c).getBytes()) + "\"";
149       break;
150
151     case Constants.CONSTANT_Utf8: str = ((ConstantUtf8)c).getBytes(); break;
152     case Constants.CONSTANT_Double: str = "" + ((ConstantDouble)c).getBytes(); break;
153     case Constants.CONSTANT_Float: str = "" + ((ConstantFloat)c).getBytes(); break;
154     case Constants.CONSTANT_Long: str = "" + ((ConstantLong)c).getBytes(); break;
155     case Constants.CONSTANT_Integer: str = "" + ((ConstantInteger)c).getBytes(); break;
156
157     case Constants.CONSTANT_NameAndType:
158       str = (constantToString(((ConstantNameAndType)c).getNameIndex(),
159                   Constants.CONSTANT_Utf8) + " " +
160          constantToString(((ConstantNameAndType)c).getSignatureIndex(),
161                   Constants.CONSTANT_Utf8));
162       break;
163
164     case Constants.CONSTANT_InterfaceMethodref: case Constants.CONSTANT_Methodref:
165     case Constants.CONSTANT_Fieldref:
166       str = (constantToString(((ConstantCP)c).getClassIndex(),
167                   Constants.CONSTANT_Class) + "." +
168          constantToString(((ConstantCP)c).getNameAndTypeIndex(),
169                   Constants.CONSTANT_NameAndType));
170       break;
171
172     default: // Never reached
173
throw new RuntimeException JavaDoc("Unknown constant type " + tag);
174     }
175     
176     return str;
177   }
178
179   private static final String JavaDoc escape(String JavaDoc str) {
180     int len = str.length();
181     StringBuffer JavaDoc buf = new StringBuffer JavaDoc(len + 5);
182     char[] ch = str.toCharArray();
183
184     for(int i=0; i < len; i++) {
185       switch(ch[i]) {
186       case '\n' : buf.append("\\n"); break;
187       case '\r' : buf.append("\\r"); break;
188       case '\t' : buf.append("\\t"); break;
189       case '\b' : buf.append("\\b"); break;
190       case '"' : buf.append("\\\""); break;
191       default: buf.append(ch[i]);
192       }
193     }
194
195     return buf.toString();
196   }
197
198
199   /**
200    * Retrieve constant at `index' from constant pool and resolve it to
201    * a string representation.
202    *
203    * @param index of constant in constant pool
204    * @param tag expected type
205    * @return String representation
206    */

207   public String JavaDoc constantToString(int index, byte tag)
208        throws ClassFormatError JavaDoc
209   {
210     Constant c = getConstant(index, tag);
211     return constantToString(c);
212   }
213
214   /**
215    * Dump constant pool to file stream in binary format.
216    *
217    * @param file Output file stream
218    * @throw IOException
219    */

220   public void dump(DataOutputStream file) throws IOException
221   {
222     file.writeShort(constant_pool_count);
223
224     for(int i=1; i < constant_pool_count; i++)
225       if(constant_pool[i] != null)
226     constant_pool[i].dump(file);
227   }
228
229   /**
230    * Get constant from constant pool.
231    *
232    * @param index Index in constant pool
233    * @return Constant value
234    * @see Constant
235    */

236   public Constant getConstant(int index) {
237     if (index >= constant_pool.length || index < 0)
238       throw new ClassFormatError JavaDoc("Invalid constant pool reference: " +
239                  index + ". Constant pool size is: " +
240                  constant_pool.length);
241     return constant_pool[index];
242   }
243
244   /**
245    * Get constant from constant pool and check whether it has the
246    * expected type.
247    *
248    * @param index Index in constant pool
249    * @param tag Tag of expected constant, i.e., its type
250    * @return Constant value
251    * @see Constant
252    * @throw ClassFormatError
253    */

254   public Constant getConstant(int index, byte tag)
255        throws ClassFormatError JavaDoc
256   {
257     Constant c;
258
259     c = getConstant(index);
260
261     if(c == null)
262       throw new ClassFormatError JavaDoc("Constant pool at index " + index + " is null.");
263
264     if(c.getTag() == tag)
265       return c;
266     else
267       throw new ClassFormatError JavaDoc("Expected class `" + Constants.CONSTANT_NAMES[tag] +
268                  "' at index " + index + " and got " + c);
269   }
270
271   /**
272    * @return Array of constants.
273    * @see Constant
274    */

275   public Constant[] getConstantPool() { return constant_pool; }
276   /**
277    * Get string from constant pool and bypass the indirection of
278    * `ConstantClass' and `ConstantString' objects. I.e. these classes have
279    * an index field that points to another entry of the constant pool of
280    * type `ConstantUtf8' which contains the real data.
281    *
282    * @param index Index in constant pool
283    * @param tag Tag of expected constant, either ConstantClass or ConstantString
284    * @return Contents of string reference
285    * @see ConstantClass
286    * @see ConstantString
287    * @throw ClassFormatError
288    */

289   public String JavaDoc getConstantString(int index, byte tag)
290        throws ClassFormatError JavaDoc
291   {
292     Constant c;
293     int i;
294     String JavaDoc s;
295
296     c = getConstant(index, tag);
297
298     /* This switch() is not that elegant, since the two classes have the
299      * same contents, they just differ in the name of the index
300      * field variable.
301      * But we want to stick to the JVM naming conventions closely though
302      * we could have solved these more elegantly by using the same
303      * variable name or by subclassing.
304      */

305     switch(tag) {
306     case Constants.CONSTANT_Class: i = ((ConstantClass)c).getNameIndex(); break;
307     case Constants.CONSTANT_String: i = ((ConstantString)c).getStringIndex(); break;
308     default:
309       throw new RuntimeException JavaDoc("getConstantString called with illegal tag " + tag);
310     }
311
312     // Finally get the string from the constant pool
313
c = getConstant(i, Constants.CONSTANT_Utf8);
314     return ((ConstantUtf8)c).getBytes();
315   }
316   /**
317    * @return Length of constant pool.
318    */

319   public int getLength()
320   {
321     return constant_pool_count;
322   }
323
324   /**
325    * @param constant Constant to set
326    */

327   public void setConstant(int index, Constant constant) {
328     constant_pool[index] = constant;
329   }
330
331   /**
332    * @param constant_pool
333    */

334   public void setConstantPool(Constant[] constant_pool) {
335     this.constant_pool = constant_pool;
336     constant_pool_count = (constant_pool == null)? 0 : constant_pool.length;
337   }
338   /**
339    * @return String representation.
340    */

341   public String JavaDoc toString() {
342     StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
343
344     for(int i=1; i < constant_pool_count; i++)
345       buf.append(i + ")" + constant_pool[i] + "\n");
346
347     return buf.toString();
348   }
349
350   /**
351    * @return deep copy of this constant pool
352    */

353   public ConstantPool copy() {
354     ConstantPool c = null;
355
356     try {
357       c = (ConstantPool)clone();
358     } catch(CloneNotSupportedException JavaDoc e) {}
359
360     c.constant_pool = new Constant[constant_pool_count];
361
362     for(int i=1; i < constant_pool_count; i++) {
363       if(constant_pool[i] != null)
364     c.constant_pool[i] = constant_pool[i].copy();
365     }
366
367     return c;
368   }
369 }
370
Popular Tags