Best practice to look up Java Enum

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

    We do all our enums like this when it comes to Rest/Json etc. It has the advantage that the error is human readable and also gives you the accepted value list. We are using a custom method MyEnum.fromString instead of MyEnum.valueOf, hope it helps.

    public enum MyEnum {
    
        A, B, C, D;
    
        private static final Map NAME_MAP = Stream.of(values())
                .collect(Collectors.toMap(MyEnum::toString, Function.identity()));
    
        public static MyEnum fromString(final String name) {
            MyEnum myEnum = NAME_MAP.get(name);
            if (null == myEnum) {
                throw new IllegalArgumentException(String.format("'%s' has no corresponding value. Accepted values: %s", name, Arrays.asList(values())));
            }
            return myEnum;
        }
    }
    

    so for example if you call

    MyEnum value = MyEnum.fromString("X");
    

    you'll get an IllegalArgumentException with the following message:

    'X' has no corresponding value. Accepted values: [A, B, C, D]

    you can change the IllegalArgumentException to a custom one.

提交回复
热议问题