Created
July 26, 2014 10:07
-
-
Save asaskevich/4c6dee9169095fa2477f to your computer and use it in GitHub Desktop.
Java Reflection - Remove "private final" modifiers and set/get value to field
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
package sandbox; | |
import java.lang.reflect.Field; | |
import java.lang.reflect.Modifier; | |
public class MainSandBox { | |
public static void main(String[] args) throws Exception { | |
Example ex = new Example(); | |
// Change private modifier to public | |
Field f = ex.getClass().getDeclaredField("id"); | |
f.setAccessible(true); | |
// Remove final modifier | |
Field modifiersField = Field.class.getDeclaredField("modifiers"); | |
modifiersField.setAccessible(true); | |
modifiersField.setInt(f, f.getModifiers() & ~Modifier.FINAL); | |
// Get and set field value | |
Integer old_value = (Integer) f.get(ex); | |
f.set(ex, 20); | |
Integer new_value = (Integer) f.get(ex); | |
// OUTPUT | |
System.out.println("ex1:\n" + old_value + "\n" + new_value); | |
Example ex2 = new Example(); | |
Field f2 = ex2.getClass().getDeclaredField("id"); | |
f2.setAccessible(true); | |
// Get and set field value | |
Integer old_value_2 = (Integer) f2.get(ex2); | |
System.out.println("ex2:\n" + old_value_2); | |
} | |
} | |
class Example { | |
private final int id = 10; | |
} |
This fails in JDK 17 (probably since JDK 12+) because "Field.modifier" is not available any more.
The approach at https://stackoverflow.com/a/71465198/411846 seems to be working for me.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This solution is incomplete (won't cover the 'override' case), and it can be easier, see this: http://stackoverflow.com/questions/3301635/change-private-static-final-field-using-java-reflection/31268945#31268945