Skip to content

Instantly share code, notes, and snippets.

@DasBrain
Created December 8, 2020 10:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DasBrain/25c6738610c517ee375aacc86ffebd0c to your computer and use it in GitHub Desktop.
Save DasBrain/25c6738610c517ee375aacc86ffebd0c to your computer and use it in GitHub Desktop.
Demostrates that changing static final fields may not work.
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
class Main {
static class Value {
public static final Integer VALUE = 10;
}
static void setFinalField(Field field, Object newValue) throws Exception {
field.setAccessible(true);
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(null, newValue);
}
static Integer getField() {
for (int i = 0; i < 1_000_000; i++) {
if (Value.VALUE != 10) {
return Value.VALUE;
}
}
return Value.VALUE;
}
public static void main(String args[]) throws Exception {
getField();
System.out.println(getField());
setFinalField(Value.class.getField("VALUE"), 200);
System.out.println("set VALUE to 200");
System.out.println(getField());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment