Enum枚举类的优雅用法

一、声明一个通用接口

/**
 * 枚举类通用接口
 * @author Administrator
 *
 * @param 
 */
public interface CommonEnum {
	
	Object getCode();

}

二、声明枚举类

public enum EMessageCode implements CommonEnum{
	
	/* 全局通用异常 */
	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 
	 * @param code
	 * @param enumClass
	 * @return
	 */
	public static  T getEnumByCode(Object code, Class enumClass) {
		for (T each : enumClass.getEnumConstants()) {
			if (each.getCode().equals(code)) {
				return each;
			}
		}
		return null;
	}

}

 

 

你可能感兴趣的:(java)