java枚举类常见操作

x33g5p2x  于2022-02-09 转载在 Java  
字(1.6k)|赞(0)|评价(0)|浏览(486)

java枚举类常见操作

  1. public enum Status {
  2. OK(0, "成功"),
  3. ERROR_A(100, "错误A"),
  4. ERROR_B(200, "错误B");
  5. Status(int number, String description) {
  6. this.code = number;
  7. this.description = description;
  8. }
  9. private int code;
  10. private String description;
  11. public int getCode() {
  12. return code;
  13. }
  14. public String getDescription() {
  15. return description;
  16. }
  17. //根据code查找description
  18. public static String getValue(int v) {
  19. for (Status s : Status.values()) {
  20. if (v==s.getCode()){
  21. return s.getDescription();
  22. }
  23. }
  24. return "";
  25. }
  26. //判断Status里是否有此code
  27. public static boolean isInclude(String co) {
  28. for (OpenBusinessEnum s : OpenBusinessEnum.values()) {
  29. if (co.equals(s.getCode())){
  30. return true;
  31. }
  32. }
  33. return false;
  34. }
  35. //获取所有的description
  36. public static String[] getValue() {
  37. String[] arry = new String[Status.values().length];
  38. int i = 0;
  39. for (Status s : Status.values()) {
  40. arry[i] = s.getDescription();
  41. i++;
  42. }
  43. return arry;
  44. }
  45. //判断该枚举中是否含有传入的值
  46. public static boolean contains(String test) {
  47. for (Status c : Status.values()) {
  48. if (c.name().equals(test)) {
  49. return true;
  50. }
  51. }
  52. return false;
  53. }
  54. }

测试

  1. System.out.println(Status.getde(0));//查找Status枚举中code是0的description的值。输出:成功
  2. System.out.println(Status.valueOf("OK").getCode());//查找Status枚举中OK的code。输出:0
  3. System.out.println(Status.valueOf("OK").getDescription());//查找Status枚举中OK的description。输出:成功
  4. System.out.println(Status.OK); //输出:OK
  5. System.out.println(Status.OK.getCode()); //输出:0
  6. System.out.println(Status.OK.getDescription()); //输出:成功
  7. System.out.println(Arrays.asList(Status.getde()));//输出:[成功, 错误A, 错误B]
  8. String event1 = "aaa";
  9. String event2 = "ERROR_B";
  10. System.out.println(Status.contains(event1));//false。因为Status中不含有aaa
  11. System.out.println(Status.contains(event2));//true。因为Status中含有ERROR_B

相关文章

最新文章

更多