All pastes #1620221 Raw Edit

InvokeDynamic Hello example

public java v1 · immutable
#1620221 ·published 2009-10-14 18:52 UTC
rendered paste body
import java.dyn.*;public class Hello {    public static void main(String... av) throws Throwable {        if (av.length == 0)  av = new String[] { "world" };        greeter(av[0] + " (from a statically linked call site)");        for (String whom : av) {            greeter.<void>invoke(whom);  // strongly typed direct call            // previous line generates invokevirtual MethodHandle.invoke(String)void            InvokeDynamic.hail(whom);      // weakly typed invokedynamic            // previous line generates invokedynamic MethodHandle.invoke(String)Object        }    }    public static void greeter(String x) { System.out.println("Hello, "+x); }    // intentionally pun between the method and its reified handle:    static MethodHandle greeter        = MethodHandles.lookup().findStatic(Hello.class, "greeter",                                   MethodType.make(void.class, String.class));    // Set up a class-local bootstrap method.    static { Linkage.registerBootstrapMethod("bootstrapInvokeDynamic"); }     // Note:  The Linkage API is subject to change.    static Object bootstrapInvokeDynamic(CallSite site, Object... args) throws Throwable {        assert(args.length == 1 && site.name() == "hail");  // in lieu of MOP        System.out.println("set target to adapt "+greeter);        MethodHandle target = MethodHandles.convertArguments(greeter, site.type());        site.setTarget(target);        System.out.println("calling the slow path; this should be the last time!");        return MethodHandles.invoke(target, args);    }}