由于类型推断,我正在尝试运行以下代码,它在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)可以正常工作。
知道为什么吗?
发布于 2016-08-18 18:34:43
每当您创建一个带有签名的泛型方法,该方法承诺返回调用方所希望的任何内容,您就是在自找麻烦。您应该从编译器那里得到一个“未经检查”的警告,这基本上意味着:可能会发生意外的ClassCastException。
您希望编译器能够推断
List<CB> bl1 = Arrays.asList(YourClass.<CA,CB>convert(a));而编译器实际上推断
List<CB> bl1 = Arrays.asList(YourClass.<CA,CB[]>convert(a));据我所知,因为它更喜欢不需要varargs打包的方法调用(这与之前的varargs代码兼容)。
这将失败,因为您的convert方法不返回预期的数组类型。
https://stackoverflow.com/questions/39021934
复制相似问题