解决方案:枚举类根据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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM