Created
March 2, 2023 05:16
-
-
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
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
/** | |
* 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