Best practice to look up Java Enum

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

    update: As GreenTurtle correctly remarked, the following is wrong


    I would just write

    boolean result = Arrays.asList(FooEnum.values()).contains("Foo");
    

    This is possibly less performant than catching a runtime exception, but makes for much cleaner code. Catching such exceptions is always a bad idea, since it is prone to misdiagnosis. What happens when the retrieval of the compared value itself causes an IllegalArgumentException ? This would then be treaten like a non matching value for the enumerator.

提交回复
热议问题