Last active
July 1, 2020 14:02
-
-
Save LunNova/2ac088d93fb411bd7240c9dd6c7cdc7f to your computer and use it in GitHub Desktop.
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 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"); | |
field.setAccessible(true); | |
return (MethodHandles.Lookup) field.get(null); | |
} | |
@Test | |
public void test() throws Throwable { | |
val lookup = getImplLookup(); | |
val baseHandle = lookup.findSpecial(Base.class, "toString", | |
MethodType.methodType(String.class), | |
Sub.class); | |
val objectHandle = lookup.findSpecial(Object.class, "toString", | |
MethodType.methodType(String.class), | |
// Must use Base.class here for this reference to call Object's toString | |
Base.class); | |
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 { | |
@Override | |
public String toString() { | |
return "Sub"; | |
} | |
} | |
public class Base { | |
@Override | |
public String toString() { | |
return "Base"; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment