首页 > 解决方案 > 泛型 - “捕获”不能应用于“?”

问题描述

泛型错误消息中的“”是什么caputure<?>意思?考虑以下示例:

interface Model<T> { T get(); }

static class DefaultModel<T> implements Model<T> {
    final T t;
    public DefaultModel(T t) { this.t = t; }
    @Override public T get() { return t; }
}

interface CellPopulator<T> {}

interface Column<T,S> extends CellPopulator<T> {}

static class Row {}

public static class Table<T,S> {
    public void updateCellItem(Model<Column<T,S>> model) {}
}

类型使用与未解决的冲突:

public static void main(String[] args) {
    Model<CellPopulator<Row>> gridCellModel = null;

    Table<Row,?> table = new Table<>();
    Column<Row,?> tableCell = (Column<Row, ?>) gridCellModel.get();
    Model<Column<Row,?>> tableCellModel = new DefaultModel<>(tableCell);

    // Model<Column<Row,capture<?>>> can not be applied to Model<Column<Row,?>>
    table.updateCellItem(tableCellModel); // COMPILATION ERROR
}

标签: javagenerics

解决方案


推荐阅读