三元条件运算符中的不兼容类型

Incompatible types in ternary conditional operator

我正在尝试根据特定条件为下拉框设置自定义渲染器:

themeComboBox.setRenderer(
    settings == null ? themeComboBox.getRenderer() : new ThemeNameRenderer());

其中 themeComboBoxjavax.swing.JComboBox<Path> 的实例,ThemeNameRenderer 是扩展 DefaultListCellRenderer.

的自定义 class

编译不通过,出现如下错误

method setRenderer in class JComboBox<E> cannot be applied to given types;
    themeComboBox.setRenderer(settings == null ? themeComboBox.getRenderer() : new ThemeNameRenderer());
  required: ListCellRenderer<? super Path>
  found: ListCellRenderer<CAP#1>
  reason: actual argument ListCellRenderer<CAP#1> cannot be converted to ListCellRenderer<? super Path> by method invocation conversion
  where E is a type-variable:
    E extends Object declared in class JComboBox
  where CAP#1 is a fresh type-variable:
    CAP#1 extends Object from capture of ? extends Object

如何使用条件运算符使其工作?


他们似乎在 Java 8 中对类型推断进行了一些改进,这或许可以解释行为上的差异。

检查此页面中的 "Target Types" 部分:

https://docs.oracle.com/javase/tutorial/java/generics/genTypeInference.html

The notion of what is a target type has been expanded to include method arguments

使用 Java 1.7(需要添加强制转换),这段代码对我来说编译得很好:

themeComboBox.setRenderer(
            (ListCellRenderer<? super Path>) (settings == null ? themeComboBox.getRenderer() : new ThemeNameRenderer()));

并且您的原始代码使用 Java 1.8:

编译得很好
themeComboBox.setRenderer(
            settings == null ? themeComboBox.getRenderer() : new ThemeNameRenderer());