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()

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。

推薦閱讀: