1. 程式人生 > >DTO 中返回 Enum 類的通用寫法

DTO 中返回 Enum 類的通用寫法

1.寫一個通用介面

public interface CodeEnum<T> {
    T getCode();
}

2.列舉類中實現介面

@Getter
public enum OrderStatusEnum implements CodeEnum<Integer> {
    NEW(0, "新訂單"),
    FINISHED(1, "完結"),
    CANCEL(2, "已取消"),;

    private Integer code;
    private String msg;

    OrderStatusEnum(Integer code, String msg) {
        
this.code = code; this.msg = msg; } }

3.建一個工具 類

public class EnumUtil {
    public static <T extends CodeEnum> T getByCode(Integer code, Class<T> enumClass) {
        for (T each : enumClass.getEnumConstants()) {
            if (code.equals(each.getCode())) {
                
return each; } } return null; } }

4.dto 類中引用

@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; //訂單狀態 預設0新訂單 private Integer orderStatus; //支付狀態 預設0未支付 private Integer payStatus; // @JsonSerialize // @DateTimeFormat(pattern = "yyyy-MM-dd") @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") private Date createTime; private Date updateTime; List<OrderDetail> orderDetailList; @JsonIgnore //物件轉json 格式可以忽略 public OrderStatusEnum getOrderStatusEnum() { return EnumUtil.getByCode(orderStatus, OrderStatusEnum.class); } }