Skip to content

Instantly share code, notes, and snippets.

@gerixx
Last active October 14, 2019 11:10
Show Gist options
  • Save gerixx/03a05385805e7663e60e8d48cc9b06e4 to your computer and use it in GitHub Desktop.
Save gerixx/03a05385805e7663e60e8d48cc9b06e4 to your computer and use it in GitHub Desktop.
Java reflection example to change final member
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
// Extended code from https://stackoverflow.com/questions/3301635/change-private-static-final-field-using-java-reflection
// to support change of final members of an instance.
public class ReflectionChangeFinalMember {
static void setFinalMemberOfObject(Object target, Field field, Object newValue) throws Exception {
field.setAccessible(true);
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.set(field, field.getModifiers() & ~Modifier.FINAL);
field.set(target, newValue);
}
public static void main(String args[]) throws Exception {
Map<Integer, String> changedMap = new HashMap<Integer, String>() {
{
put(1, "UNO");
}
};
A a = new A();
System.out.printf("A.getSteOne = %s%n", a.getStepOne()); // original map
Field stepsField = a.getClass().getDeclaredField("steps");
setFinalMemberOfObject(a, stepsField, changedMap);
System.out.printf("A.getSteOne = %s%n", a.getStepOne()); // changed map
}
}
class A {
private final Map<Integer, String> steps = Collections.unmodifiableMap(new HashMap<Integer, String>() {
{
put(1, "one");
}
});
public String getStepOne() {
return steps.get(1);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment