java - 用于继承的java抽象类
问题描述
我有一个项目,我目前正在使用 org.apache.poi 将记录从 excel 文件加载到数据库
我有 3 种文件要加载到不同的 Dto 类中。其中两个 dto 共享相同的基类(它们具有共同的属性)
@Getter
@Setter
@ToString
public class PpyRecordDTO {
private String units;
private Double quantity;
}
@Getter
@Setter
@ToString
public class FirstRecordDTO extends RecordDTO {
private String normDescription;
private String relatedUnits;
}
@Getter
@Setter
@ToString
public class SecondRecordDTO extends RecordDTO{
private String normName;
}
@Getter
@Setter
@ToString
public class ThirdRecordDTO {
private String code;
}
ThirdRecordDto 类具有唯一属性,并且没有与基 dto 类 RecordDTO 共享的属性
我想从此方法返回基类:RecordDto(但 ThirdRecordDTO 无法扩展它,因为没有公共字段)
public static List<?extends RecordDTO> readPpyExcelFile(MultipartFile file, SourceType sourceType){
//TODO: making readPpyExcelFile generic
try {
Workbook workbook = WorkbookFactory.create(new BufferedInputStream(file.getInputStream()));
Sheet sheet = workbook.getSheetAt(0);
Iterator<Row> rows = sheet.iterator();
List<? extends RecordDTO> lstRecords = processRecords(rows, sourceType);
// Close WorkBook
workbook.close();
return lstRecords;
} catch(ApiGenericException apiException){
throw new ApiGenericException(apiException.getStatus(), apiException.getMessage(), apiException.getErrorType());
} catch (Exception e) {
logger.error(e.getMessage());
throw new ApiGenericException(HttpStatus.INTERNAL_SERVER_ERROR,"Enable while loading the file", ApiErrorType.Unhandled
);
}
}
有没有办法让 dto ThirdRecordDto 也被返回或从其他 dto 共享的抽象类继承以返回类型 <?从此方法扩展列表?
解决方案
一般来说,你可以使用这样的东西:
public interface Ppy {
// common methods if any
}
public class PpyRecordDTO implements Ppy{...}
public class FirstRecordDTO extends PpyRecordDTO {...} // so that it also implements Ppy interface
public class SecondRecordDTO extends PpyRecordDTO {...} // the same as above
public class ThirdRecordDTO implements Ppy {...} // Note, it doesn't extend PpyRecordDTO but implements the interface
现在在该方法中,可以:
public static List<Ppy> readPpyExcelFile(MultipartFile file, SourceType sourceType){...}
这将起作用,但是,您应该问自己以下问题:调用此方法的代码将做什么,即它将如何区分不同的实现?如果接口有一个对所有实现都有意义的通用方法——很好,它将能够调用该方法。例如,如果它有类似的方法render(Page)
或其他东西,代码可能是:
List<Ppy> ppis = readPpyExcelFile(...);
Page page = ...
for(Ppy ppi : ppis) {
ppi.render(page);
}
但是,如果接口没有任何常用方法 - 它不会有太大帮助。当子对象可以被视为父对象的特化时使用继承(因此子对象“是”父对象)。所以想想继承在这里是否真的合适,假设ThirdRecordDTO
与其他类没有任何共同之处。
推荐阅读
- django - 当我在 Django PostgreSQL 中使用 shell 创建对象时,ID 序列化不会更新
- mysql - CloudSQL - MySql - 导入后内存泄漏
- javascript - Laravel中ajax分页的页面加载
- laravel - HTPP 请求 Ajax 转换为 Laravel 用于外部 api
- python - 为什么`numpy`向下舍入`0.025`而不是向上舍入
- r - 从异方差稳健标准模型中提取残差
- django - 多对多关系中的缓存更新
- typescript - 如何使用 TypeScript 在 Vue 组件中添加自定义属性,而不需要 TypeScript 大喊大叫?
- elasticsearch - 弹性搜索全文搜索
- azure - SSAS 仅限于一个分区