001: // Copyright (c) 2000 Per M.A. Bothner.
002: // This is free software; for terms and warranty disclaimer see ./COPYING.
003:
004: package gnu.bytecode;
005:
006: import java.io.*;
007:
008: /* Represents the contents of a standard "ConstantValue" attribute.
009: * @author Per Bothner
010: */
011:
012: public class ConstantValueAttr extends Attribute {
013: Object value;
014: int value_index;
015:
016: public Object getValue(ConstantPool cpool) {
017: if (value != null)
018: return value;
019: CpoolEntry entry = cpool.getPoolEntry(value_index);
020: switch (entry.getTag()) {
021: case ConstantPool.STRING:
022: value = ((CpoolString) entry).getString().getString();
023: break;
024: case ConstantPool.INTEGER:
025: value = new Integer(((CpoolValue1) entry).value);
026: break;
027: case ConstantPool.LONG:
028: value = new Long(((CpoolValue2) entry).value);
029: break;
030: case ConstantPool.FLOAT:
031: float f = Float.intBitsToFloat(((CpoolValue1) entry).value);
032: value = new Float(f);
033: break;
034: case ConstantPool.DOUBLE:
035: double d = Double
036: .longBitsToDouble(((CpoolValue2) entry).value);
037: value = new Double(d);
038: break;
039: }
040: return value;
041: }
042:
043: public ConstantValueAttr(Object value) {
044: super ("ConstantValue");
045: this .value = value;
046: }
047:
048: public ConstantValueAttr(int index) {
049: super ("ConstantValue");
050: this .value_index = index;
051: }
052:
053: public void assignConstants(ClassType cl) {
054: super .assignConstants(cl);
055: if (value_index == 0) {
056: ConstantPool cpool = cl.getConstants();
057: CpoolEntry entry = null;
058: if (value instanceof String)
059: entry = cpool.addString((String) value);
060: else if (value instanceof Integer)
061: entry = cpool.addInt(((Integer) value).intValue());
062: else if (value instanceof Long)
063: entry = cpool.addLong(((Long) value).longValue());
064: else if (value instanceof Float)
065: entry = cpool.addFloat(((Float) value).floatValue());
066: else if (value instanceof Long)
067: entry = cpool.addDouble(((Double) value).doubleValue());
068: value_index = entry.getIndex();
069: }
070: }
071:
072: public final int getLength() {
073: return 2;
074: }
075:
076: public void write(DataOutputStream dstr) throws java.io.IOException {
077: dstr.writeShort(value_index);
078: }
079:
080: public void print(ClassTypeWriter dst) {
081: dst.print("Attribute \"");
082: dst.print(getName());
083: dst.print("\", length:");
084: dst.print(getLength());
085: dst.print(", value: ");
086: if (value_index == 0) {
087: Object value = getValue(dst.ctype.constants);
088: if (value instanceof String)
089: dst.printQuotedString((String) value);
090: else
091: dst.print(value);
092: } else {
093: if (dst.printConstants) {
094: dst.print(value_index);
095: dst.print('=');
096: }
097: CpoolEntry entry = dst.ctype.constants
098: .getPoolEntry(value_index);
099: entry.print(dst, 1);
100: }
101: dst.println();
102: }
103: }
|