Created
June 10, 2017 20:43
-
-
Save jnape/3e8d8cbaa6f2d3ce41a4bb489ecc30f6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class WreckedCast { | |
@SuppressWarnings("unchecked") | |
static <P, PP extends Parametric<P>> PP wreckedCast(Parametric<? extends Parametric<P>> ppp) { | |
return (PP) ppp.extract(); | |
} | |
public static void main(String[] args) { | |
// java.lang.ClassCastException: WreckedCast$Parametric$$Lambda$1/1607521710 cannot be cast to java.lang.String | |
System.out.println(wreckedCast(Parametric.parametric(Parametric.parametric(1)))); | |
//this doesn't help | |
System.out.println(wreckedCast(Parametric.<Parametric<Integer>>parametric(Parametric.parametric(1)))); | |
//not even this helps | |
Parametric<Parametric<Integer>> parametric = Parametric.parametric(Parametric.parametric(1)); | |
System.out.println(wreckedCast(parametric)); | |
Parametric<Integer> onlyWorksIfExplicitlyTyped = wreckedCast(Parametric.parametric(Parametric.parametric(1))); | |
System.out.println(onlyWorksIfExplicitlyTyped); | |
/* | |
For some reason I'm not yet sure of, javac is determining that the appropriate println() overload to dispatch | |
to is println(String), rather than println(Object), even though, regardless of what Parametric is, it can't | |
possibly be a String. | |
Thus, the resulting bytecode is generated: | |
CHECKCAST java/lang/String | |
INVOKEVIRTUAL java/io/PrintStream.println (Ljava/lang/String;)V | |
Naturally, the CHECKCAST blows up. | |
Interestingly, changing wreckedCast's argument's covariant bound on Parametric<P> to be invariant, resulting | |
in the argument Parametric<Parametric<P>>, also resolves this. | |
*/ | |
} | |
public interface Parametric<P> { | |
P extract(); | |
static <P> Parametric<P> parametric(P p) { | |
return () -> p; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment