Skip to content

Instantly share code, notes, and snippets.

@asaskevich
Created July 26, 2014 10:07
Show Gist options
  • Save asaskevich/4c6dee9169095fa2477f to your computer and use it in GitHub Desktop.
Save asaskevich/4c6dee9169095fa2477f to your computer and use it in GitHub Desktop.
Java Reflection - Remove "private final" modifiers and set/get value to field
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;
}
@centic9
Copy link

centic9 commented Jan 5, 2023

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