Skip to content

Instantly share code, notes, and snippets.

@EvaGL
Created October 9, 2020 16:15
Show Gist options
  • Save EvaGL/77a165c6e8bf2ad316d44e509ee9b6a3 to your computer and use it in GitHub Desktop.
Save EvaGL/77a165c6e8bf2ad316d44e509ee9b6a3 to your computer and use it in GitHub Desktop.
Mad reflection
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