Skip to content

Instantly share code, notes, and snippets.

@jnape
Last active March 12, 2016 06:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jnape/8358e9a9d7985d49046e to your computer and use it in GitHub Desktop.
Save jnape/8358e9a9d7985d49046e to your computer and use it in GitHub Desktop.
Java8 invokeinterface type-unification bug
package example;
import java.util.Optional;
class Foo {}
interface Bar {
String barMethod();
}
public class TypeUnifailcation extends Foo implements Bar {
@Override
public String barMethod() {
return "now you see me...";
}
public static <T extends Foo & Bar> void win(T t) {
Optional.of(t)
.map(x -> x.barMethod()) // invokestatic to anonymous synthetic lambda
.ifPresent(System.out::println);
}
public static <T extends Foo & Bar> void alsoWin(T t) {
Optional.<Bar>of(t)
.map(Bar::barMethod) // invokeinterface with type specified by parametricity (Bar)
.ifPresent(System.out::println);
}
public static <T extends Foo & Bar> void fail(T t) {
// might as well go ahead and compile successfully
// and just produce invalid byte code
Optional.of(t)
.map(Bar::barMethod) // invokeinterface with wrong type (Foo)
.ifPresent(System.out::println);
}
public static void main(String... args) {
TypeUnifailcation example = new TypeUnifailcation();
win(example);
alsoWin(example);
fail(example);
}
}
@pedrofurla
Copy link

$ java example.TypeUnifailcation
now you see me...
now you see me...
Exception in thread "main" java.lang.BootstrapMethodError: call site initialization exception
    at java.lang.invoke.CallSite.makeSite(CallSite.java:341)
    at java.lang.invoke.MethodHandleNatives.linkCallSiteImpl(MethodHandleNatives.java:307)
    at java.lang.invoke.MethodHandleNatives.linkCallSite(MethodHandleNatives.java:297)
    at example.TypeUnifailcation.fail(TypeUnifailcation.java:31)
    at example.TypeUnifailcation.main(TypeUnifailcation.java:40)
Caused by: java.lang.invoke.LambdaConversionException: Invalid receiver type class example.Foo; not a subtype of implementation type interface example.Bar
    at java.lang.invoke.AbstractValidatingLambdaMetafactory.validateMetafactoryArgs(AbstractValidatingLambdaMetafactory.java:233)
    at java.lang.invoke.LambdaMetafactory.metafactory(LambdaMetafactory.java:303)
    at java.lang.invoke.CallSite.makeSite(CallSite.java:302)
    ... 4 more

@jnape
Copy link
Author

jnape commented Mar 12, 2016

Exactly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment