Created
October 9, 2020 16:15
-
-
Save EvaGL/77a165c6e8bf2ad316d44e509ee9b6a3 to your computer and use it in GitHub Desktop.
Mad reflection
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.reflect.Constructor; | |
import java.lang.reflect.Method; | |
class A { | |
public void foo() { | |
System.out.println(1); | |
} | |
} | |
class B extends A { | |
public void foo() { | |
System.out.println(2); | |
} | |
} | |
class Main { | |
public static void main(String[] args) throws Throwable { | |
Constructor<MethodHandles.Lookup> constructor = MethodHandles.Lookup.class.getDeclaredConstructor(Class.class); | |
constructor.setAccessible(true); | |
Method method = A.class.getDeclaredMethod("foo"); | |
A instance = new B(); | |
method.invoke(instance); // prints 2 | |
constructor.newInstance(A.class) | |
.in(A.class) | |
.unreflectSpecial(method, A.class) | |
.bindTo(instance) | |
.invoke(); // prints 1 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment