JDK8 type pin

I am trying to run the following code that compiled under JDK8, thanks to the type of output:

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 method throws a ClassCastException: CB cannot be passed to [Ljava.lang.Object, but CB b = convert (a) works fine.

Any idea why?

+4
java-8 type-inference javac classcastexception
source share
1 answer

Whenever you create a generic method with a signature that promises returns all the wishes of the caller, you ask for troubles. You should receive an β€œunverified” warning from the compiler, which basically means: an unexpected ClassCastException may occur.

You expect the compiler to conclude

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

whereas the compiler actually deduced

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

as far as I know, because he prefers method calls that don't require varargs packaging (which is compatible with pre-varargs code).

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

+3
source share

All Articles