What's the best practice to "look up" Java Enums?

Posted by Marcus on Stack Overflow See other posts from Stack Overflow or by Marcus
Published on 2010-03-10T16:44:10Z Indexed on 2010/03/17 15:51 UTC
Read the original article Hit count: 259

Filed under:
|
|

We have a REST API where clients can supply parameters representing values defined on the server in Java Enums.

So we can provide a descriptive error, we add this lookup method to each Enum. Seems like we're just copying code (bad). Is there a better practice?

public enum MyEnum {
    A, B, C, D;

    public static MyEnum lookup(String id) {
        try {
            return MyEnum.valueOf(id);
        } catch (IllegalArgumentException e) {
            throw new RuntimeException("Invalid value for my enum blah blah: " + id);
        }
    }
}

Update: The default error message provided by valueOf(..) would be No enum const class a.b.c.MyEnum.BadValue. I would like to provide a more descriptive error from the API.

© Stack Overflow or respective owner

Related posts about java

Related posts about enum