Best practice to look up Java Enum

前端 未结 10 836
甜味超标
甜味超标 2021-02-01 13:17

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

10条回答
  •  执笔经年
    2021-02-01 13:41

    Probably you can implement generic static lookup method.

    Like so

    public class LookupUtil {
       public static > E lookup(Class 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.

提交回复
热议问题