I have some code that processes fixed length data records. I've defined the record structures using java enums. I've boiled it down the the simplest example possible to illustrate the hoops that I currently have to jump through to get access to a static variable inside the enum. Is there a better way to get at this variable that I'm overlooking? If you compile and run the code, it converts each string into an XML chunk. I've done the XML manually so that the example is simpler, but my real code uses Java DOM.
EDIT: I've updated the code to a more complete example that I think better shows what I'm trying to do.
class EnumTest
{
public static void main(String args[])
{
System.out.println( parse("ABC", RecordType1.class) );
System.out.println( parse("ABCDEF", RecordType2.class) );
}
private interface RecordLayout {
public int length();
}
private enum RecordType1 implements RecordLayout {
FIELD1 (2),
FIELD2 (1),
;
private int length;
private RecordType1(int length) { this.length = length; }
public int length() { return length; }
public static int RECORD_LEN = 3;
}
private enum RecordType2 implements RecordLayout {
FIELD1 (5),
FIELD2 (1),
;
private int length;
private RecordType2(int length) { this.length = length; }
public int length() { return length; }
public static int RECORD_LEN = 6;
}
private static <E extends Enum<E> & RecordLayout> String parse(String data, Class<E> record) {
// ugly hack to get at RECORD_LEN...
int len = 0;
try {
len = record.getField("RECORD_LEN").getInt(record);
}
catch (Exception e) { System.out.println(e); }
String results = "<RECORD length=\"" + len + "\">\n";
int curPos = 0;
for (E field: record.getEnumConstants()) {
int endPos = curPos + field.length();
results += " <" + field.toString() + ">"
+ data.substring(curPos, endPos)
+ "</" + field.toString() + ">\n";
curPos = endPos;
}
results += "</RECORD>\n";
return results;
}
}