Hi all.
Making a small program that will read a .class file and display information. Using this as a reference point:
VM Spec The class File Format
It describes the class file format, hopefully in an accurate way. Anyway, I am trying to figure out a good way to read from the constant pool. If you read that link, in the section about the constant pool, it talks about several structures that are very similar. So I could just use a class hierarchy. Thing is, I am the master of complicating things for myself, and I am not sure what the best way to represent the different stuff would be. For example, here are two of the classes:
Base class:
public abstract class CPInfo { // Declare the tag holding variable protected int mTag; /** * Returns the tag of this cp info thing * * @return the tag */ public int tag() { return mTag; } /** * ============ * === TAGS === * ============ */ public static final int TAG_CLASS = 7; public static final int TAG_FIELD_REF = 9; public static final int TAG_METHOD_REF = 10; public static final int TAG_INTERFACE_METHOD_REF = 11; public static final int TAG_STRING = 8; public static final int TAG_INTEGER = 3; public static final int TAG_FLOAT = 4; public static final int TAG_LONG = 5; public static final int TAG_DOUBLE = 6; public static final int TAG_NAME_AND_TYPE = 12; public static final int TAG_UTF8 = 1; }
Represents an integer in the constant pool.
public class CPInteger extends CPInfo { private int mInt; public CPInteger(int intval) throws ClassFormatException { super.mTag = CPInfo.TAG_INTEGER; mInt = intval; } public int value() { return mInt; } }
Represents a float in the constant pool:
As you can see, they are basically identical, except that one stores an int and one stores a float. Not happy with it, to be honest, since they are so similar. It feels like I could create a better way to do this. Anyone has a better idea of how to do this? Or is this the best way? I am getting a headache when I think of it too much, lol (figuratively speaking).public class CPFloatInfo extends CPInfo { private float mFloat; public CPFloatInfo(float floatval) { super.mTag = CPInfo.TAG_FLOAT; mFloat = floatval; } public float value() { return mFloat; } }
And do note that at the moment I am just trying to replicate the structure of a class file until I get a better grip of what I am actually doing. Have not done this before, so to be honest, I have no idea what I am doing.
Take care,
Kerr
EDIT:
One option would be to simply have an object in the CPInfo class and then cast it to whatever data I need (in the case of int and float I would use the Integer or Float classes). Could work, but not very type safe. Not that the way I am currently doing it is any better, for that matter...