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

前端 未结 27 2204
旧巷少年郎
旧巷少年郎 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:56

    You should also be careful with your case. Let me explain: doing Blah.valueOf("A") works, but Blah.valueOf("a") will not work. Then again Blah.valueOf("a".toUpperCase(Locale.ENGLISH)) would work.

    edit
    Changed toUpperCase to toUpperCase(Locale.ENGLISH) based on tc. comment and the java docs

    edit2 On android you should use Locale.US, as sulai points out.

提交回复
热议问题