解决方案:枚举类根据key值获取value值

下面是一个根据key值获取枚举类相应的value值的方法。

第一种方法

  1. public static String getValue(String code) {
  2. for (TestEnum ele : values()) {
  3. if(ele.getCode().equals(code)) return ele.getValue();
  4. }
  5. return null;
  6. }

第二种方法

  1. 枚举类
  2. public enum Test {
  3. A("Hello",0),B("World",1);
  4. private String name;
  5. private int code;
  6. public String getName() {
  7. return name;
  8. }
  9. public void setName(String name) {
  10. this.name = name;
  11. }
  12. public int getCode() {
  13. return code;
  14. }
  15. public void setCode(int code) {
  16. this.code = code;
  17. }
  18. private Test(String name, int code) {
  19. this.name = name;
  20. this.code = code;
  21. }
  22. }
  23. 测试类
  24. public static void main(String[] args) {
  25. System.out.println(Enum.valueOf(Test.class,"A").getCode());
  26. }

注意:建议优先使用第一种。

原文地址:https://blog.csdn.net/en_joker/article/details/85044179
posted @ 2019-12-27 13:53  星朝  阅读(7002)  评论(0编辑  收藏  举报