Enum枚举类的优雅用法
程序员文章站
2022-06-16 13:50:05
...
一、声明一个通用接口
/**
* 枚举类通用接口
* @author Administrator
*
* @param <T>
*/
public interface CommonEnum<T> {
Object getCode();
}
二、声明枚举类
public enum EMessageCode implements CommonEnum<EMessageCode>{
/* 全局通用异常 */
RESOURCE_NOT_EXIST("00000","资源不存在"),
PARAM_ERROR("00001","参数错误"),
NUKNOW_ERROR("99999","未知异常"),
/* 订单相关异常 */
ORDER_CREATE_FAIL("10000","下单失败"),
/* 商品相关异常 */
PRODUCT_STOCK_NOT_ENOUGH("20000","库存不足"),
;
private String code;
private String message;
private EMessageCode(String code, String message) {
this.code = code;
this.message = message;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
三、声明一个通用的枚举工具类
public class EnumUtils {
/**
* 根据code获取枚举类
* @param <T>
* @param code
* @param enumClass
* @return
*/
public static <T extends CommonEnum> T getEnumByCode(Object code, Class<T> enumClass) {
for (T each : enumClass.getEnumConstants()) {
if (each.getCode().equals(code)) {
return each;
}
}
return null;
}
}