下面是一个根据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

相关文章:

  • 2022-12-23
  • 2022-03-05
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-09
猜你喜欢
  • 2022-12-23
  • 2021-10-19
  • 2022-12-23
  • 2022-12-23
  • 2021-07-22
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案