Created
October 18, 2015 08:18
-
-
Save pditommaso/263721865d84dee6ebaf to your computer and use it in GitHub Desktop.
Change type and value of a final field in a Java/Groovy class
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
static class TestJ3 { | |
static final Integer f = 1 | |
static public void set(String str) { | |
Field field = TestJ3.class.getDeclaredField("f") | |
Field modifiersField = Field.class.getDeclaredField("modifiers") | |
modifiersField.setAccessible(true) | |
modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL) | |
Field fieldType = Field.getDeclaredField("type") | |
fieldType.setAccessible(true) | |
fieldType.set(field, String.class) | |
field.setAccessible(true) | |
field.set(null, str) | |
} | |
} | |
TestJ3.set("Hello") | |
assert TestJ3.f == "Hello" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Courtesy of https://twitter.com/nicolas_frankel/status/655303856298065920