Java枚举根据参数获取对应值

public enum ChangeHandleEnum {

    CHANGE_HANDLE_MESSAGE_KEY1(1, "type1", "消息1"),
    CHANGE_HANDLE_MESSAGE_KEY2(2, "type2", "消息2"),
    CHANGE_HANDLE_MESSAGE_KEY3(3, "type3", "消息3"),
    CHANGE_HANDLE_MESSAGE_KEY4(4, "type4", "消息4");

    private Integer keyId;

    private String type;

    private String message;

    ChangeHandleEnum(Integer keyId, String type, String message){
        this.keyId = keyId;
        this.type = type;
        this.message = message;
    }

    public static String getMessageByKeyId(Integer keyId) {
        ChangeHandleEnum[] changeHandleEnums = values();
        for (ChangeHandleEnum changeHandleEnum : changeHandleEnums) {
            if (changeHandleEnum.getKeyId().equals(keyId)) {
                return changeHandleEnum.getMessage();
            }
        }
        return null;
    }

    public static String getTypeByKeyId(Integer keyId) {
        ChangeHandleEnum[] changeHandleEnums = values();
        for (ChangeHandleEnum changeHandleEnum : changeHandleEnums) {
            if (changeHandleEnum.getKeyId().equals(keyId)) {
                return changeHandleEnum.getType();
            }
        }
        return null;
    }

    public Integer getKeyId() {
        return keyId;
    }

    public String getType() {
        return type;
    }

    public String getMessage() {
        return message;
    }
}

 调用方法:

比如这里我们根据keyId获取message,

String message = ChangeHandleEnum.getMessageByKeyId(1);
System.out.println(message);    //message1

  

posted @ 2020-11-13 16:41  木马不是马  阅读(3649)  评论(0编辑  收藏  举报