Best practice to look up Java Enum

前端 未结 10 842
甜味超标
甜味超标 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:52

    If you want the lookup to be case insensitive you can loop through the values making it a little more friendly:

     public enum MyEnum {
       A, B, C, D;
    
          public static MyEnum lookup(String id) {
            boolean found = false;
            for(MyEnum enum: values()){
               if(enum.toString().equalsIgnoreCase(id)) found = true;
            }  
            if(!found) throw new RuntimeException("Invalid value for my enum: " +id);
           }
    }
    

提交回复
热议问题