gpt4 book ai didi

java - 处理集合的通用函数

转载 作者:行者123 更新时间:2023-12-01 11:16:34 25 4
gpt4 key购买 nike

我有一个这样的功能

    private void writeResultsIntoSheets(WritableWorkbook workbook, List<JournalEntry> summaries) throws WriteException, RowsExceededException {
String sheetName = "Journal Entry Summary";

WritableSheet sheet = workbook.getSheet(sheetName);
if (sheet == null) {
int sheetIndex = 0;
if (workbook.getNumberOfSheets() > 0) sheetIndex = workbook.getNumberOfSheets()-1;
sheet = workbook.createSheet(sheetName, sheetIndex); //add behind
}

Integer row = 0;

int col = -1;
sheet.addCell(new Label(++col, row, "SN"));
sheet.addCell(new Label(++col, row, "Account Name"));
sheet.addCell(new Label(++col, row, "Currency"));
sheet.addCell(new Label(++col, row, "Amount"));
sheet.addCell(new Label(++col, row, "Created On"));

for (JournalEntry s : summaries) {
row++;

//write data
col = -1;
sheet.addCell(new Label(++col, row, (row) + "."));
sheet.addCell(new Label(++col, row, s.getAccount().getName()));
sheet.addCell(new Label(++col, row, s.getCurrency().getCode()));
sheet.addCell(new Label(++col, row, String.valueOf(s.getAmount())));
sheet.addCell(new Label(++col, row, String.valueOf(s.getCreatedOn())));

}
}

基本上,它将读取 JournalEntry 实体列表,并将特定值写入 Excel 文件的行中。现在我必须对其他十几个实体执行相同的操作,每个实体都有不同的值要写下来。我如何将它变成一个通用函数并应用于其他函数?

最佳答案

使用模板模式:

public abstract class SheetWriter<T> {
private final void writeResultsIntoSheets(WritableWorkbook workbook, List<T> summaries) throws WriteException, RowsExceededException {
String sheetName = getSheetName();

WritableSheet sheet = workbook.getSheet(sheetName);
if (sheet == null) {
int sheetIndex = 0;
if (workbook.getNumberOfSheets() > 0) sheetIndex = workbook.getNumberOfSheets()-1;
sheet = workbook.createSheet(sheetName, sheetIndex); //add behind
}

int row = 0;
writeHeadings(sheet, row);

for (T s : summaries) {
row++;
writeRow(sheet, s, row);
}
}

protected abstract String getSheetName();
protected abstract void writeHeadings(WritableSheet sheet, int row) throws WriteException;
protected abstract void writeRow(WritableSheet sheet, T item, int row) throws WriteException;
}

然后,对于每个实体,定义 SheetWriter 的子类并实现 3 个抽象方法。

关于java - 处理集合的通用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31760957/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com