Skip to content

Instantly share code, notes, and snippets.

@duncte123
Forked from asaskevich/MainSandBox.java
Created January 25, 2019 08:17
Show Gist options
  • Save duncte123/79e3e77265918699ba7486d1ec9182ad to your computer and use it in GitHub Desktop.
Save duncte123/79e3e77265918699ba7486d1ec9182ad 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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment