枚举类型不但可以用来直观地定义常量,同时还可以定义和该常量相关的一些属性。
最基本的用法:
/**
* Redis的Key类型
*/
public enum KeyType {
string, list, set, zset, hash;
}
如果要获得“string”、“list”等字符串,可以这样使用:
KeyType.string.name();
KeyType.list.name();
KeyType.zset.toString();
KeyType.hash.toString();
带有一个相关属性的定义和用法,需要定义一个构造方法来接收这个属性(enum类中的构造方法缺省是private类型,无法定义为其他类型):
/**
* 以秒为单位的时间常量。先定义,再使用,提高代码可读性
*/
public enum TimeInSecond {
/** 5天 */
_5_DAYS(5*24*3600),
/** 24小时 */
_24_HOURS(24*3600),
/** 8小时 */
_8_HOURS(8*3600),
/** 120分钟 */
_120_MINS(120*60),
/** 10分钟 */
_10_MINS(10*60),
/** 5分钟 */
_5_MINS(5*60),
/** 无穷大 ≈68年 */
INFINITE(Integer.MAX_VALUE),
/** 不指定有效期,比如根据不同情况使用不同的有效期的情况、或其他不适用的情况 */
NA(Integer.MIN_VALUE);
TimeInSecond(int seconds){
this.seconds = seconds;
}
public int val() {
return seconds;
}
private int seconds;
}
获取相关属性的使用方法:
int ttl = TimeInSecond._5_DAYS.val();
带有多个相关属性的定义和用法,同时定义几个参数列表不同的构造方法来接收相关的属性:
/**
* Redis Key的前缀:前缀String、类型、有效期(秒)
* 类型如果不指定则默认为string
* 有效期如果不指定则默认为5天
*/
public enum Prefix {
/** APP登录的token前缀,value=userId */
APP_TOKEN("token.to.userid:"),
/** WEB登录的token前缀,value=userId */
WEB_TOKEN("web.token.to.userid:", TimeInSecond._24_HOURS),
/** UserInfo信息,APP登录和WEB登录共用 */
USER_INFO("user.info:", KeyType.hash),
/** 验证码,Hash类型, 后面跟着cookieId */
CAPTCHA("captcha:", KeyType.hash, TimeInSecond._5_MINS),
/**
* 定义了前缀,缺省类型为string、有效期5天
*/
Prefix(String id){
this.id = id;
this.type = KeyType.string;
this.ttl = TimeInSecond._5_DAYS;
}
/**
* 定义了前缀和有效期,缺省类型为string
*/
Prefix(String id, TimeInSecond ttl){
this.id = id;
this.type = KeyType.string;
this.ttl = ttl;
}
/**
* 定义了前缀和类型,缺省有效期5天
*/
Prefix(String id, KeyType type){
this.id = id;
this.type = type;
this.ttl = TimeInSecond._5_DAYS;
}
/**
* 定义了前缀、类型、和有效期
*/
Prefix(String id, KeyType type, TimeInSecond ttl){
this.id = id;
this.type = type;
this.ttl = ttl;
}
public String id() {
return id;
}
public String type() {
return type.name();
}
public int ttl() {
return ttl.val();
}
@Override
public String toString() {
return id;
}
private String id; //前缀字符串
private KeyType type; //类型
private TimeInSecond ttl; //过期时间(秒)
}
使用方法:
String prefix = Prefix.APP_TOKEN.id();
String webKey = Prefix.WEB_TOKEN + "abc"; //会自动调用toString()方法
String userInfoKeyType = Prefix.USER_INFO.type();
int captchaTtl = Prefix.CAPTCHA.ttl();
注意:改enum类重写了toString()方法,是为了方便使用第二种调用方法(它会自动调用toString()方法)。如果不重写,它返回的是和name()相同的结果。
遍历一个枚举中所有定义的值:
for(Prefix p : Prefix.values()){
//do someThing;
}
遍历一般用于通过某个相关属性找到相对应的枚举类,比如,通过"web.token.to.userid:"找到WEB_TOKEN。可以加一个static方法来实现这个功能:
/**
* 根据id返回一个Prefix
* @param id
* @return Prefix 或 null
*/
public static Prefix getPrefix (int id){
for(Prefix p : Prefix.values()){
if(p.id()==id){
return p;
}
}
return null;
}