首页 > 编程语言 > Java灵活使用枚举表示一组字符串的操作
2021
08-20

Java灵活使用枚举表示一组字符串的操作

Java枚举表示一组字符串

public class HelloWorld {
    public static void main(String []args) {
       System.out.println("Hello World!");
		System.out.println(Season.SPRING.toString());
		System.out.println(Season.SPRING.value());
    }
}
enum Season {
	SPRING("spring"), SUMMER("summer"), AUTUMN("autumn"), WINTER("winter");
	
	public final String value;
	private Season(String value) {
		this.value = value;
	}
	
	public String value() {
		return this.value;
	}
}

程序输出结果如下:

Hello World!
SPRING
spring

Java枚举类的正确使用

规范使用枚举类

public enum StatEnum {
    SUCCESS(1,"成功"),
    FAILD(0,"失败"),
    REPEAT(-1,"重复"),
    INNER_ERROR(-2,"系统异常"),
    DATA_ERROR(-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 {
    SUCCESS(0, "成功"),
    DAILD(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()

以上为个人经验,希望能给大家一个参考,也希望大家多多支持自学编程网。

编程技巧