Last active
January 19, 2018 16:56
-
-
Save headius/9369ccd68714b57ace4328d70f3b946e to your computer and use it in GitHub Desktop.
"Hello, %s" using method handles two different ways
This file contains hidden or 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
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