枚举类为:
public enum OrderStatusEnum implements CondeEnum{ NEW(0, "新订单"), FINISHED(1, "完结"), CANCLE(2, "取消"); private Integer code; private String msg; OrderStatusEnum(Integer code, String msg) { this.code = code; this.msg = msg; } public Integer getCode() { return code; } public String getMsg() { return msg; } }
实现的接口为:
public interface CondeEnum<T> { T getCode(); }
然后实现一个工具类:
public class EnumUtil { public static <T extends CondeEnum> T getByCode(Integer code, Class<T> enumClass) { for (T each : enumClass.getEnumConstants()) { if (code.equals(each.getCode())) { return each; } } return null; } }
在实体类中直接进行赋值:
@Data @JsonInclude(JsonInclude.Include.NON_NULL) public class OrderDTO { private String orderId; private String buyerName; private String buyerPhone; private String buyerAddress; private String buyerOpenid; private BigDecimal orderAmount; private Integer orderStatus = OrderStatusEnum.NEW.getCode(); private Integer payStatus = PayStatusEnum.WAIT.getCode(); @JsonSerialize(using = Date2LongSerializer.class) private LocalDateTime createTime; @JsonSerialize(using = Date2LongSerializer.class) private LocalDateTime updateTime; private List<OrderDetail> orderDetailList; @JsonIgnore public OrderStatusEnum getOrderStatusEnum() { return EnumUtil.getByCode(orderStatus, OrderStatusEnum.class); } @JsonIgnore public PayStatusEnum getPayStatusEnum() { return EnumUtil.getByCode(payStatus, PayStatusEnum.class); } }