Groovy关闭委派不委派给子对象

xzv2uavs  于 2022-10-07  发布在  其他
关注(0)|答案(1)|浏览(155)

我有这段代码,用于处理数据源电子表格的两个不同的工作表。我有一些BaseRecordHandler专门用于处理电子表格本身。它包含方法

protected void initDataSourceFile() throws IOException {
        File file = new File(this.dataSourceFilename);
        this.excelFile = this.getWorkbook(file);

        if (file.exists())
            return;

        file.getParentFile().mkdirs();

        FileOutputStream outputStream = new FileOutputStream(file);

        this.setupSpreadsheet({ Sheet sheet ->
            setupFirstRow(sheet.createRow(0));

            sheet.createFreezePane(0, 1);

            // returning the sheet allows for the functional programming technique known as composition
            return sheet;
        });

        this.excelFile.write(outputStream);
        outputStream.close();
        this.excelFile.close();
    }

实际的电子表格处理程序PracticeProfileHandler有两个子BaseSheetHandler。其setupSpreadsheet()定义为:

@Override
    protected void setupSpreadsheet(Closure<Sheet> onSetupSheet) {

        Closure onGetAndSetupSheet = SMDSpreadsheetUtils.OnCreateIfNotExistSheet(this.excelFile) >> onSetupSheet;

        this.childPracticeURLHandler = new PracticeURLHandler(onGetAndSetupSheet);
        this.childOrgNameHandler = new OrganizationNameHandler(onGetAndSetupSheet);
    }

    @Override
    protected void setupFirstRow(Row firstRow) {
        throw new Exception("PracticeProfileHandler should not be trying to set up the first row of a Sheet");
    }

BaseSheetHandler定义如下:

public abstract class BaseSheetHandler<T> {
    protected Sheet sheet;
    protected List<T> usedRecords;

    protected BaseSheetHandler(Closure<Sheet> onGetSheet) {
        onGetSheet.setDelegate(this);
        this.sheet = onGetSheet(this.getSheetName());
        this.init();
    }

    // ...rest of code...
}

子处理程序的fillInRow()在其各自的类上实现。

问题是,当我点击这个practiceProfileHandler.initDataSourceFile()时,它的行为就像子fillInRow()不存在一样,而是点击PracticeProfileHandler上的那个,尽管我将包含该行代码的回调委托给子示例本身(通过BaseSheetHandler构造函数)!

是什么导致了这种情况的发生,以及我如何修复它?

7kjnsjlb

7kjnsjlb1#

根据@emilles建议,我在BaseSheetHandler构造函数中设置了解析策略:

protected BaseSheetHandler(Closure<Sheet> onGetSheet) {
        onGetSheet.setResolveStrategy(Closure.DELEGATE_FIRST);
        onGetSheet.setDelegate(this);
        this.sheet = onGetSheet(this.getSheetName());
        this.init();
    }

而且它起作用了!

我应该把这个写在某个闭包实用程序类上...!

相关问题