枚举类enum的使用

枚举类的作用是罗列并规范一些全局的常量,替代static final一起定义的常量,并约定常量的取值范围。只需要将常量类型定义为相应的枚举类,就可以对某个常量进行约束。下面给出两种枚举类的用法:

1.不带参数的成员变量

public enum HttpMethodEnum {
    DELETE,
    GET,
    POST,
    PUT;

    private HttpMethodEnum() {
    }
}

在这里插入图片描述
如上,约定method的值只能有DELETE、GET、POST、PUT。

2.带参数的成员变量

public interface BaseEnum {
    public String getValue();
}
public enum ContentTypeEnum implements BaseEnum{
    APPLICATION_JSON("application/json"){
        @Override
        public String getValue() {
            return "application/json";
        }
    },
    APPLICATION_FORM("application/x-www-form-urlencoded"){
        @Override
        public String getValue() {
            return "application/x-www-form-urlencoded";
        }
    },
    MULTIPART_FORM_DATA("multipart/form-data"){
        @Override
        public String getValue() {
            return "multipart/form-data";
        }
    };

    private final String contentType;

    private ContentTypeEnum(String contentType) {
        this.contentType = contentType;
    }

    public String getContentType(){
        return this.contentType;
    }
}

在这里插入图片描述
contentType的值只能为APPLICATION_JSON、APPLICATION_FORM、MULTIPART_FORM_DATA,通过给contentType传递这三个中的任意一个值,将其对应的参数赋给成员变量contentType,通过getContentType()方法就可以拿到值application/json、application/x-www-form-urlencoded、multipart/form-data。

枚举类的switch使用:
在这里插入图片描述

contentType.getContentType().equals(ContentTypeEnum.APPLICATION_JSON.getValue())
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值