Last active
February 10, 2017 21:02
-
-
Save DenWav/abf2906174dd184cd89d64daa0ab03ed 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
package com.demonwav.stupid; | |
import java.lang.reflect.Field; | |
import java.lang.reflect.Method; | |
import java.lang.reflect.Modifier; | |
public class Main { | |
public static final Object helloWorldHolder = new Object() { | |
private final Object words = "Goodbye World!"; | |
}; | |
public static final Object stringPrinter = new Object() { | |
private void printString(Object object) { | |
System.out.println(object); | |
} | |
}; | |
public static void main(String[] args) throws Throwable { | |
setField(helloWorldHolder, "words", "Hello World!"); | |
forMethod(stringPrinter, "printString", Object.class).call(getField(helloWorldHolder, "words")); | |
} | |
public static class MethodCaller { | |
private final Class<?> aClass; | |
private final Object object; | |
private final String method; | |
private final Class<?>[] types; | |
public MethodCaller(Class<?> aClass, Object object, String method, Class<?>[] types) throws Throwable { | |
this.aClass = aClass; | |
this.object = object; | |
this.method = method; | |
this.types = types; | |
} | |
public Object call(Object... params) throws Throwable { | |
final Method declaredMethod = aClass.getDeclaredMethod(method, types); | |
declaredMethod.setAccessible(true); | |
return declaredMethod.invoke(object, params); | |
} | |
} | |
public static MethodCaller forMethod(Object object, String method, Class<?>... types) throws Throwable { | |
final Class<?> aClass = object.getClass(); | |
return new MethodCaller(aClass, object, method, types); | |
} | |
public static Object getField(Object object, String field) throws Throwable { | |
final Class<?> aClass = object.getClass(); | |
final Field declaredField = aClass.getDeclaredField(field); | |
declaredField.setAccessible(true); | |
return declaredField.get(object); | |
} | |
public static Object setField(Object object, String field, Object value) throws Throwable { | |
final Class<?> aClass = object.getClass(); | |
final Field declaredField = aClass.getDeclaredField(field); | |
declaredField.setAccessible(true); | |
if (Modifier.isFinal(declaredField.getModifiers())) { | |
final Field modifiers = declaredField.getClass().getDeclaredField("modifiers"); | |
modifiers.setAccessible(true); | |
modifiers.setInt(declaredField, declaredField.getModifiers() & ~Modifier.FINAL); | |
} | |
final Object oldVal = getField(object, field); | |
declaredField.set(object, value); | |
return oldVal; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment