枚举类的作用是罗列并规范一些全局的常量,替代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())