Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
import lombok.val;
import org.junit.Assert;
import org.junit.Test;
import java.lang.invoke.*;
Your scientists were so preoccupied with whether or not they could, they didn’t stop to think if they should.
Please don't actually do this... :P
public class ImplLookupTest {
private MethodHandles.Lookup getImplLookup() throws NoSuchFieldException, IllegalAccessException {
val field = MethodHandles.Lookup.class.getDeclaredField("IMPL_LOOKUP");
return (MethodHandles.Lookup) field.get(null);
public void test() throws Throwable {
val lookup = getImplLookup();
val baseHandle = lookup.findSpecial(Base.class, "toString",
val objectHandle = lookup.findSpecial(Object.class, "toString",
// Must use Base.class here for this reference to call Object's toString
val sub = new Sub();
Assert.assertEquals("Sub", sub.toString());
Assert.assertEquals("Base", baseHandle.invoke(sub));
Assert.assertEquals(toString(sub), objectHandle.invoke(sub));
private static String toString(Object o) {
return o.getClass().getName() + "@" + Integer.toHexString(o.hashCode());
public class Sub extends Base {
public String toString() {
return "Sub";
public class Base {
public String toString() {
return "Base";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.