Skip to content

Instantly share code, notes, and snippets.

@headius
Last active January 19, 2018 16:56
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save headius/9369ccd68714b57ace4328d70f3b946e to your computer and use it in GitHub Desktop.
Save headius/9369ccd68714b57ace4328d70f3b946e to your computer and use it in GitHub Desktop.
"Hello, %s" using method handles two different ways
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
public class Hello {
private static final MethodHandles.Lookup lookup = MethodHandles.lookup();
public static void main(String[] args) throws Throwable {
System.out.println("Hello, " + args[0]);
}
public static void main(String[] args) throws Throwable {
MethodHandle streamH = lookup.findStaticGetter(System.class, "out", PrintStream.class);
MethodHandle nameH = MethodHandles.arrayElementGetter(String[].class);
nameH = MethodHandles.insertArguments(nameH, 1, 0);
MethodHandle concatH = lookup.findVirtual(String.class, "concat", MethodType.methodType(String.class, String.class));
concatH = concatH.bindTo("Hello, ");
MethodHandle printlnH = lookup.findVirtual(PrintStream.class, "println", MethodType.methodType(void.class, String.class));
printlnH = MethodHandles.foldArguments(printlnH, MethodHandles.dropArguments(streamH, 0, String.class));
MethodHandle helloH = MethodHandles.filterArguments(printlnH, 0, concatH);
helloH = MethodHandles.filterArguments(helloH, 0, nameH);
helloH.invoke(args);
}
public static void main(String[] args) throws Throwable {
MethodHandle helloH = Binder.from(void.class, String[].class)
.filter(0, String.class, b -> b.append(0).arrayGet())
.filter(0, String.class, b -> b.prepend("Hello, ").invokeVirtualQuiet(lookup, "concat"))
.fold(PrintStream.class, b -> b.dropAll().getStaticQuiet(lookup, System.class, "out"))
.invokeVirtualQuiet(lookup, "println");
helloH.invoke(args);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment