JDK8类型推断问题

JDK8 type inference issue

我正在尝试 运行 以下代码,由于类型推断,它在 JDK8 下编译得很好:

public static <A,B> B convert(A a) {
  return (B) new CB();
}
public static void main(String[] args) {
  CA a = new CA();
  CB b = convert(a); //this runs fine
  List<CB> bl = Arrays.asList(b); //this also runs fine
  List<CB> bl1 = Arrays.asList(convert(a)); //ClassCastException here
}

然而,运行宁这会抛出 ClassCastException:CB 无法转换为 [Ljava.lang.Object,但 CB b = convert(a) 工作正常。

知道为什么吗?

每当你创建一个带有签名的泛型方法时,承诺 return 无论调用者希望什么,你都是在自找麻烦。你应该从编译器那里得到一个“未经检查”的警告,这基本上意味着:可能会发生意外的 ClassCastExceptions。

您希望编译器推断

List<CB> bl1 = Arrays.asList(YourClass.<CA,CB>convert(a));

而编译器实际上推断

List<CB> bl1 = Arrays.asList(YourClass.<CA,CB[]>convert(a));

据我所知,因为它更喜欢不需要可变参数包装的方法调用(与预可变参数代码兼容)。

失败是因为您的 convert 方法没有 return 预期的数组类型。