Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice to look up Java Enum

Tags:

java

enums

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.

like image 491
Marcus Leon Avatar asked Mar 10 '10 16:03

Marcus Leon


People also ask

How can I lookup a Java enum from its string value?

Example: Lookup enum by string value We then use the enum TextStyle's valueOf() method to pass the style and get the enum value we require. Since valueOf() takes a case-sensitive string value, we had to use the toUpperCase() method to convert the given string to upper case.

Are enums bad practice?

Many people consider Enums as a code smell and an anti-pattern in OOPs. Certain books have also cited enums as a code smell, such as the following. In most cases, enums smell because it's frequently abused, but that doesn't mean that you have to avoid them. Enums can be a powerful tool in your arsenal if used properly.

How do you use enums correctly?

You should always use enums when a variable (especially a method parameter) can only take one out of a small set of possible values. Examples would be things like type constants (contract status: “permanent”, “temp”, “apprentice”), or flags (“execute now”, “defer execution”).


1 Answers

Probably you can implement generic static lookup method.

Like so

public class LookupUtil {    public static <E extends Enum<E>> E lookup(Class<E> e, String id) {          try {                    E result = Enum.valueOf(e, id);       } catch (IllegalArgumentException e) {          // log error or something here           throw new RuntimeException(            "Invalid value for enum " + e.getSimpleName() + ": " + id);       }        return result;    } } 

Then you can

public enum MyEnum {    static public MyEnum lookup(String id) {        return LookupUtil.lookup(MyEnum.class, id);    } } 

or call explicitly utility class lookup method.

like image 65
Mykola Golubyev Avatar answered Oct 13 '22 00:10

Mykola Golubyev