Skip to content

Instantly share code, notes, and snippets.

@bryder
Last active March 3, 2017 00:37
Show Gist options
  • Save bryder/7ead8ce97f44741d938cf7b1715393ba to your computer and use it in GitHub Desktop.
Save bryder/7ead8ce97f44741d938cf7b1715393ba to your computer and use it in GitHub Desktop.
how to change private variables in java
// Using java.lang.reflect
Field field = instanceOfAClass.getClass().getDeclaredField("nameOfThePrivateVariable");
field.setAccessible(true);
Map<UUID, Long> nameOfThePrivateVariable = (Map<UUID, Long>)field.get(instanceOfAClass);
nameOfThePrivateVariable.put(aNewKey, aNewValue);
// Using org.springframework.test.util.ReflectionTestUtils
// There may be typos in the below!
Cache<UUID, UUID> aCache = (Cache<UUID, UUID>)ReflectionTestUtils.getField(instanceOfObjectWithCacheAsPrivateField, "aCache");
aCache.invalidateAll();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment