本文介绍了JDK8类型推断问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to run the following code which is compiled fine under JDK8 thanks to type inference:

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)可以正常工作.

However, running this throws ClassCastException: CB cannot be cast to [Ljava.lang.Object, but the CB b = convert(a) works fine.

知道为什么吗?

推荐答案

每当您创建带有签名的通用方法时,该方法承诺会返回调用者希望的任何内容,这是在自找麻烦.您应该从编译器处收到未经检查"的警告,这基本上意味着:可能发生意外的ClassCastException.

Whenever you create a generic method with a signature that promises to return whatever the caller wishes, you are asking for trouble. You should have got an "unchecked" warning from the compiler which basically means: unexpected ClassCastExceptions may occur.

您希望编译器进行推断

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

编译器实际推断出

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

据我所知,因为它更喜欢不需要varargs包装的方法调用(与varargs之前的代码兼容).

as far as I know, because it prefers method invocations not requiring a varargs packaging (which is compatible with pre-varargs code).

此操作失败,因为您的convert方法未返回预期的数组类型.

This fails because your convert method does not return the expected array type.

这篇关于JDK8类型推断问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-26 18:25