定义接口。用于反射范式编程
public interface CodeEnum {
Integer getCode();
}
定义业务枚举,并实现CodeEnum接口
/** 婚姻状况 枚举*/
public enum MaritalStatusEnum implements CodeEnum{
SPINSTERHOOD(1, "未婚"),
MARRIED_NO_CHILD(2,"已婚无子女"),
MARRIED_HAS_CHILD(3,"已婚有子女"),
DIVORCE(4,"离异");
private Integer code;
private String message;
public Integer getCode() {
return code;
}
public String getMessage() {
return message;
}
MaritalStatusEnum(Integer code, String message) {
this.code = code;
this.message = message;
}
}
定义枚举工具类
/** 枚举工具类 */
public class EnumUtil {
/** 通过code获取枚举*/
public static <T extends CodeEnum> T getEnumByCode(Integer code, Class<T> enumClass) {
for (T each : enumClass.getEnumConstants()) {
if(code.equals(each.getCode())){
return each;
}
}
return null;
}
}
使用范例:
EnumUtil.getEnumByCode(1, MaritalStatusEnum.class).getMessage();
网友评论