Java生成DTO类

时间:2017-06-26 12:11:16

标签: java inheritance refactoring dto

我有三个类,其中两个扩展基类,它们看起来像这样:

public class AllowanceDTO extends BaseExpenseDTO {
    private String flight;
}

public class CarTravelDTO extends BaseExpenseDTO {
    private Double tripLength;
}

public class BaseExpenseDTO implements Serializable {
    private static final long serialVersionUID = 1L;
    private int count = 0;
    private BigDecimal amount;
    private String typeName;
}

这些dto是TravelItemDTO

的一部分
public class TravelItemDTO implements Serializable {
    private static final long serialVersionUID = 1L;
    private String startDate;
    private String endDate;
    private List<BaseExpenseDTO> expenseCompensations;
    private List<AllowanceDTO> allowanceCompensations;
    private List<CarTravelDTO> mileageCompensations;
}

我如何能够将这些dto化为灵感?例如,我不会有三个列表而是一个列表,因为一个TravelItemDTO只能有一个类型补偿列表。

2 个答案:

答案 0 :(得分:0)

假设我正确理解了您的问题,您可以对TravelItemDTO

进行一致化
public class TravelItemDTO<T extends BaseExpenseDTO> implements Serializable {
    private static final long serialVersionUID = 1L;
    private String startDate;
    private String endDate;
    private List<T> compensations;
}

然后使用它,例如:

TravelItemDTO<CarTravelDTO> carTravelItem = new TravelItemDTO<CatTravelItem>();
...

HTH。

答案 1 :(得分:0)

您可以使用通配符:

public class TravelItemDTO implements Serializable {
    private List<? extends BaseExpenseDTO> compensations;
//...
}

示例:

TravelItemDTO dto = new TravelItemDTO();
dto.setCompensations(new ArrayList<AllowanceDTO>());