0%

java枚举的使用

规范使用枚举类

public enum StatEnum {
    SUCCESS(1,"成功"),
    END(0,"失败"),
    REPEAT_KILL(-1,"重复"),
    INNER_ERROR(-2,"系统异常"),
    DATA_REWRITE(-3,"数据异常");

    private  int state;

    private  String stateInfo;

    StatEnum(int state, String stateInfo) {
        this.state = state;
        this.stateInfo = stateInfo;
    }

    public int getState() {
        return state;
    }

    public String getStateInfo() {
        return stateInfo;
    }

    public static StatEnum stateOf(int index){
        for(StatEnum state: values()){
            if(state.getState() == index){
                return state;
            }
        }
        return  null;
    }
}

枚举搭配接口一起使用

// 定义接口
public interface CodeEnum {
    Integer getCode();
    
    String getMessage();
}
// 定义枚举
public enum StatusEnum implements CodeEnum {
    UP(0, "成功"),
    DOWN(1, "失败");
    private Integer code;

    private String message;

    StatusEnum(Integer code, String message) {
        this.code = code;
        this.message = message;
    }
    
    @Override
    public Integer getCode() {
        return code;
    }

    @Override
    public String getMessage() {
        return message;
    }
}
// 定义工具类
public class EnumUtil {

    public static <T extends CodeEnum> T getByCode(Integer code, Class<T> enumClass) {
        for (T each: enumClass.getEnumConstants()) {
            if (code.equals(each.getCode())) {
                return each;
            }
        }
        return null;
    }
}

使用:

  • EnumUtil.getByCode(0, StatusEnum.class).getMessage()
  • EnumUtil.getByCode(1, StatusEnum.class).getCode()