Skip to content

Instantly share code, notes, and snippets.

@hertzsprung
Created July 28, 2011 21:32
Show Gist options
  • Save hertzsprung/1112618 to your computer and use it in GitHub Desktop.
Save hertzsprung/1112618 to your computer and use it in GitHub Desktop.
java.lang.invoke
package foo;
import static java.lang.invoke.MethodHandles.catchException;
import static java.lang.invoke.MethodHandles.publicLookup;
import static java.lang.invoke.MethodType.methodType;
public class Foo {
public void sayHello(String name) throws RuntimeException {
System.out.println("hello " + name);
throw new RuntimeException("boom!");
}
public static void exceptionHandler(RuntimeException e, Foo foo, String name) {
System.out.println(name + " went boom in " + foo);
e.printStackTrace();
}
public static void main(String[] args) throws Throwable {
catchException(
publicLookup().findVirtual(Foo.class, "sayHello", methodType(void.class, String.class)),
RuntimeException.class,
publicLookup().findStatic(Foo.class, "exceptionHandler", methodType(void.class, RuntimeException.class, Foo.class, String.class))
)
.bindTo(new Foo())
.invoke("bob");
}
}
hello bob
bob went boom in foo.Foo@fc519e2
java.lang.RuntimeException: boom!
at foo.Foo.sayHello(Foo.java:10)
at java.lang.invoke.MethodHandleImpl$GuardWithCatch.invoke_L2(MethodHandleImpl.java:1130)
at foo.Foo.main(Foo.java:25)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment