枚举工具类:封装判断是否存在这个枚举

枚举工具类:封装判断是否存在这个枚举

1. 定义一个枚举类,继承BaseEnum

public enum MethodEnum implements BaseEnum {
  /** get请求方法 */
  GET(1, "GET"),

  /** post请求方法 */
  POST(2, "POST"),

  /** put请求方法 */
  PUT(3, "PUT"),

  /** delete请求方法 */
  DELETE(4, "DELETE");

  private Integer value;
  private String name;

  MethodEnum(Integer value, String name) {
    this.value = value;
    this.name = name;
  }

  @Override
  public Integer getValue() {
    return value;
  }

  @Override
  public String getName() {
    return name;
  }

  public void setValue(Integer value) {
    this.value = value;
  }

  public void setName(String name) {
    this.name = name;
  }
}

2. BaseEnum接口

public interface BaseEnum {

  Integer getValue();

  String getName();
}

3. EnumUtils工具类封装判断

public final class EnumUtils {

  /**
   * 判断枚举值是否存在于指定枚举数组中
   *
   * @param enums 枚举数组
   * @param value 枚举值
   * @return boolean
   */
  public static boolean isExist(BaseEnum[] enums, Integer value) {
    if (value == null) {
      return false;
    }
    for (BaseEnum e : enums) {
      if (value.equals(e.getValue())) {
        return true;
      }
    }
    return false;
  }

  /**
   * 根据枚举值获取其对应的name
   *
   * @param enums 枚举数组
   * @param value 枚举值
   * @return 枚举值获取其对应的name
   */
  public static String getNameByValue(BaseEnum[] enums, Integer value) {
    if (value == null) {
      return "";
    }
    for (BaseEnum e : enums) {
      if (value.equals(e.getValue())) {
        return e.getName();
      }
    }
    return "";
  }
}

4. 测试

public class Test {
  public static void main(String[] args) {
    if (!EnumUtils.isExist(MethodEnum.values(), 5)) {
      System.out.println("错误"); //s输出错误
    }
    String nameByValue = EnumUtils.getNameByValue(MethodEnum.values(), 1);
    System.out.println(nameByValue);
  }
}

参考博文:https://blog.csdn.net/mayfly_hml/article/details/88872366

猜你喜欢

转载自www.cnblogs.com/proper128/p/13206785.html