How to get an enum value from a string value in Java?

前端 未结 27 2237
旧巷少年郎
旧巷少年郎 2020-11-21 10:53

Say I have an enum which is just

public enum Blah {
    A, B, C, D
}

and I would like to find the enum value of a string, for example

27条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-11-21 11:52

    If you don't want to write your own utility use Google's guava library:

    Enums.getIfPresent(Blah.class, "A")
    

    Unlike the built in java function it let's you check if A is present in Blah and doesn't throw an exception.

提交回复
热议问题