为什么编译器不将 T(interface) 推断为 class 在具有双界泛型类型时实现 T?

Why doesn't the compiler infer T(interface) to be class that implements T when having double bounded generic type?

我有一个 class CBound 实现了两个接口 IBound1 和 Ibound2:

class CBound implements IBound1, IBound2 {}

我有一个通用方法,它接受一个 class 类型作为类型参数,该类型同时实现了 IBound1 和 Ibound2 接口:

 public static <T extends IBound1 & IBound2> void getData(T list) {
      //Some code...
}

我用 CBound 的实现创建了一个 IBound1 类型的对象 class:

 IBound1 a = new CBound();
 getData(a); // doesn't work

为什么 obj a 不能用作 getData() 的参数?

当我用 :

更改代码时
CBound b = new CBound();
getData(b); // It works fine

编译器必须在编译时推断 T 满足边界

当你传入 a 时,编译器只知道 aIBound1 类型。由于该方法的参数也是 T,因此编译器实际上只有两个选择 T - IBound1Object - 两者都不满足边界。

您可能会问,“为什么编译器不将 T 推断为 CBound?”好吧,表达式 getData(a) 中没有任何类型为 CBound 的内容。即使我们通过阅读前面的代码行知道 a 实际上是指类型 CBound 的对象,编译器在推断 T 时也不会考虑这一点。即使 T 被推断为 CBound,您也无法将 a 传递给 CBound.

类型的参数

但是,在 b 的情况下,编译器非常清楚 bCBound 类型(因为你已经这样声明了),所以它可以成功地推断出 T 变为 CBound.