JDK8 type inference issue

风格不统一 提交于 2019-12-07 07:05:02

问题


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
}

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

Any idea why?


回答1:


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.

You expect the compiler to infer

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

whereas the compiler actually inferred

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

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

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



来源:https://stackoverflow.com/questions/39021934/jdk8-type-inference-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!