相关疑难解决方法(0)

JDK8 类型推断问题

由于类型推断,我正在尝试运行以下代码,这些代码在 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
}
Run Code Online (Sandbox Code Playgroud)

但是,运行它会抛出 ClassCastException: CB cannot be cast to [Ljava.lang.Object,但 CB b = convert(a) 工作正常。

知道为什么吗?

type-inference javac classcastexception java-8

6
推荐指数
1
解决办法
127
查看次数