-1

I have a class with a list of constants...

  public static final java.lang.String HEARTBEAT = "0";
  public static final java.lang.String TEST_REQUEST = "1";
  public static final java.lang.String RESEND_REQUEST = "2";

I would like to go from "0" -> "HEARBEAT" somehow.

Any good util classes for doing this?

DD.
  • 21,498
  • 52
  • 157
  • 246
  • I'm kind of guessing there is some apache reflection library which might help with this. – DD. Mar 28 '12 at 10:07

2 Answers2

1

I would suggest using an enum instead of constants for this to start with - then you can build up the reverse mapping within the enum.

public enum RequestType {
    HEARTBEAT("0"),
    TEST_REQUEST("1"),
    RESEND_REQUEST("2");

    private final String text;
    private static final Map<String, RequestType> reverseLookup;

    static {
        // Or use an immutable map from Guava, etc.
        reverseLookup = new HashMap<String, RequestType>();
        for (RequestType type : EnumSet.allOf(RequestType.class)) {
            reverseLookup.put(type.text, type);
        }
    }

    private RequestType(String text) {
        this.text = text;
    }

    public String getText() {
        return text;
    }

    public static RequestType getType(String text) {
        return reverseLookup.get(text);
    }
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • @DD.: It would have helped if you'd said so before. I'd still build the enum in your code, and use the 3rd party constants to provide the text values... then use the enum everywhere within your code. This will also give you more type safety. – Jon Skeet Mar 28 '12 at 10:08
  • Not really practical...There are hundreds of enums for lots of classess (this is the FIX financial exchange spec)...see http://www.quickfixj.org/quickfixj/javadoc/1.5.1/quickfix/field/MsgType.html – DD. Mar 28 '12 at 10:44
  • @DD.: Do you mean hundreds of values? Just write a tool to auto-generate the enum classes. It wouldn't take long, and would be *much* nicer than using the values everywhere, IMO. – Jon Skeet Mar 28 '12 at 10:45
1

If it is possible (as in, you're allowed to change the code), change those constants into an enum. That way, you can easily code a "reverse lookup" function by having a value associated with each enum entry.

In theory, if you have each entry representing a number from 0..N, you could even use the number of the entry (it's given by the enum), but this isn't exactly a best-practice.

Since you cannot use an enum, you can hack it through reflection (warning, it's fugly).

Accessing Java static final ivar value through reflection

This thread has some code that accesses the public static final values with reflection. You can use a Map to store this relationship, look it up in real time, or try and encapsulate this in an Enum, like Jon Skeet suggested, and use that enum from then on (with all the advantages that brings).

Community
  • 1
  • 1
pcalcao
  • 15,789
  • 1
  • 44
  • 64