Skip to content

Instantly share code, notes, and snippets.

@gregw
Created October 24, 2018 06:27
Show Gist options
  • Save gregw/b6c926fb44fd9a45b2c5afccaf7dcbf4 to your computer and use it in GitHub Desktop.
Save gregw/b6c926fb44fd9a45b2c5afccaf7dcbf4 to your computer and use it in GitHub Desktop.
test of chaining method handles
import java.io.PrintStream;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import static java.lang.invoke.MethodHandles.empty;
import static java.lang.invoke.MethodType.methodType;
public class TestMethodHandle
{
final PrintStream out = System.err;
public void callA(String s, int i)
{
out.printf("A: %s %d%n",s,i);
}
public void callB(String s, int i)
{
out.printf("B: %s %d%n",s,i);
}
public void callC(String s, int i)
{
out.printf("C: %s %d%n",s,i);
}
private static boolean alwaysTrue()
{
return true;
}
public static void main(String... arg) throws Throwable
{
TestMethodHandle test = new TestMethodHandle();
MethodHandle callA = MethodHandles.lookup().findVirtual(TestMethodHandle.class,"callA", methodType(Void.TYPE, String.class, Integer.TYPE)).bindTo(test);
MethodHandle callB = MethodHandles.lookup().findVirtual(TestMethodHandle.class,"callB", methodType(Void.TYPE, String.class, Integer.TYPE)).bindTo(test);
MethodHandle callC = MethodHandles.lookup().findVirtual(TestMethodHandle.class,"callC", methodType(Void.TYPE, String.class, Integer.TYPE)).bindTo(test);
callA.invoke("hello",0);
callB.invoke("hello",0);
callC.invoke("hello",0);
MethodHandle asGuard = MethodHandles.lookup().findStatic(TestMethodHandle.class,"alwaysTrue", MethodType.methodType(Boolean.TYPE));
MethodHandle guardA = MethodHandles.filterReturnValue(callA,asGuard);
MethodHandle guardB = MethodHandles.filterReturnValue(callB,asGuard);
MethodHandle guardC = MethodHandles.filterReturnValue(callC,asGuard);
guardA.invoke("guarded", 1);
guardB.invoke("guarded", 1);
guardC.invoke("guarded", 1);
MethodHandle empty = empty(methodType(Void.TYPE, String.class, Integer.TYPE));
MethodHandle invokeC = MethodHandles.guardWithTest(guardC,empty,empty);
MethodHandle invokeBC = MethodHandles.guardWithTest(guardB,invokeC,empty);
MethodHandle invokeABC = MethodHandles.guardWithTest(guardA,invokeBC,empty);
invokeABC.invoke("chained", 2);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment