How do I access static variables in an enum class without a class instance?

Posted by krick on Stack Overflow See other posts from Stack Overflow or by krick
Published on 2010-05-19T20:57:46Z Indexed on 2010/05/19 21:00 UTC
Read the original article Hit count: 88

Filed under:
|
|
|
|

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 just prints out "3".

Note: the "code" tag doesn't seem to want to format this properly, but it should compile.

class EnumTest {

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 LEN = 3;
}

private static <E extends Enum<E> & RecordLayout> String parse(String data, Class<E> record) {
    // ugly hack to get at LEN...
    try {
      int len = record.getField("LEN").getInt(record);
      System.out.println(len);
    }
    catch (Exception e) { System.out.println(e); }

    String results = "";
    for (E field: record.getEnumConstants()) {
      // do some stuff with the fields
    }
    return results;
}

public static void main(String args[])
{
    parse("ABC", RecordType1.class);
}

}

© Stack Overflow or respective owner

Related posts about java

Related posts about enum