Skip to content

Instantly share code, notes, and snippets.

@jorimvanhove
Created March 2, 2023 05:16
Show Gist options
  • Save jorimvanhove/8729895a342b1e45dfacf5742b07c86d to your computer and use it in GitHub Desktop.
Save jorimvanhove/8729895a342b1e45dfacf5742b07c86d to your computer and use it in GitHub Desktop.
How to change a private static final int field from outside the class in java using reflection
/**
* Copied from <a href="https://stackoverflow.com/questions/2474017/using-reflection-to-change-static-final-file-separatorchar-for-unit-testing/2474242#2474242">Stack Overflow</a>
* Do exercise extreme caution with this technique.
* Devastating consequences aside, the following actually works:
* <pre>{@code
* setFinalStatic(Boolean.class.getField("FALSE"), true);
* System.out.format("Everything is %s", false); // "Everything is true"}</pre>
*/
static void setFinalStatic(Field field, Object newValue) throws Exception {
field.setAccessible(true);
// remove final modifier from field
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(null, newValue);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment