2

现在我们正在使用 Java 7,我正在浏览一些会引发警告的旧代码。我有以下方法,它会在 Eclipse 中产生许多类型安全警告。在大多数情况下,解决方案相当简单,但该问题的默认 Eclipse 修复会导致编译错误。

 public static JList list(ListModel listModel, ListCellRenderer cellRenderer) {
    JList list = new JList();
    if (cellRenderer != null) {
        list.setCellRenderer(cellRenderer);
    }
    else {
        list.setCellRenderer(new CustomeListCellRenderer());
    }
    list.setModel(listModel);
    if (listModel != null) {
        list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    }
    return list;
}

Eclipse 将其更改为:

public static JList<?> list(ListModel<?> listModel, ListCellRenderer<?> cellRenderer) {
    JList<?> list = new JList<Object>();
    if (cellRenderer != null) {
        list.setCellRenderer(cellRenderer);
    }
    else {
        list.setCellRenderer(new CustomeListCellRenderer());
    }
    list.setModel(listModel);
    if (listModel != null) {
        list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    }
    return list;
}

这会导致错误:

The method setCellRenderer(ListCellRenderer<? super capture#4-of ?>) in the type JList<capture#4-of ?> is not applicable for the arguments (ListCellRenderer<capture#5-of?>)

The method setModel(ListModel<capture#7-of ?>) in the type JList<capture#7-of ?> is not applicable for the arguments (ListModel<capture#8-of ?>)

我觉得我不太了解泛型,无法弄清楚是什么原因造成的。我尝试从 ? 到 Object,它解决了编译错误,但我实际上不想返回 Object 类型的 JList。任何提示将不胜感激。

编辑:我将整个方法泛化为以下内容:

public static <T> JList<T> list(ListModel<T> listModel, ListCellRenderer<T> cellRenderer) {
    JList<T> list = new JList<T>();
    if (cellRenderer != null) {
        list.setCellRenderer(cellRenderer);
    }
    else {
        list.setCellRenderer(new CustomeListCellRenderer());
    }
    list.setModel(listModel);
    if (listModel != null) {
        list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    }
    return list;
}

这似乎是更新方法的适当方式吗?

4

1 回答 1

3

尝试:

public static <E> JList<E> list(ListModel<E> listModel, ListCellRenderer<? super E> cellRenderer) {
    JList<E> list = new JList<>();
    if (cellRenderer != null) {
        list.setCellRenderer(cellRenderer);
    }
    else {
        list.setCellRenderer(new CustomeListCellRenderer());
    }
    list.setModel(listModel);
    if (listModel != null) {
        list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    }
    return list;
}
于 2013-07-01T15:04:01.187 回答