Skip to content

Instantly share code, notes, and snippets.

@ololx
Created June 22, 2022 09:29
Show Gist options
  • Save ololx/54e36b95516662277eeae2c2483b48f9 to your computer and use it in GitHub Desktop.
Save ololx/54e36b95516662277eeae2c2483b48f9 to your computer and use it in GitHub Desktop.
Injecting objects in a static field - reflection hack; useful for testing, when you couldn't inject mock via constructor
package utils;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.function.Consumer;
public interface InjectUtils {
String MODIFIERS = "modifiers";
static boolean injectFinalStaticField(Class<?> clazz, String fieldName, Object newValue) {
return injectFinalStaticField(clazz, fieldName, newValue, (e) -> e.printStackTrace());
}
static boolean injectFinalStaticField(Class<?> clazz,
String fieldName,
Object newValue,
Consumer<Throwable> exceptionHandler) {
try {
Field modifiersField = Field.class.getDeclaredField(MODIFIERS);
modifiersField.setAccessible(true);
Field field = clazz.getDeclaredField(fieldName);
field.setAccessible(true);
modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(null, newValue);
modifiersField.setInt(field, field.getModifiers() | Modifier.FINAL);
field.setAccessible(false);
} catch (NoSuchFieldException | IllegalAccessException e) {
exceptionHandler.accept(e);
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment