解決方案:枚舉類根據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