Created
June 22, 2022 09:29
-
-
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
This file contains 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 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