Skip to content

Instantly share code, notes, and snippets.

@pditommaso
Created October 18, 2015 08:18
Show Gist options
  • Save pditommaso/263721865d84dee6ebaf to your computer and use it in GitHub Desktop.
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
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"
@pditommaso
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment