Skip to content

Instantly share code, notes, and snippets.

@DasBrain
Created April 12, 2022 13:02
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/ca16053f8e073c8a883bee66302c2fee to your computer and use it in GitHub Desktop.
Save DasBrain/ca16053f8e073c8a883bee66302c2fee to your computer and use it in GitHub Desktop.
package test;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
public class ChangingStaticFinalsIsStupid {
static class Value {
// It's Integer, so not a compile time constant
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 useField() {
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 {
// Comment out the next line for a different result
useField();
useField();
setFinalField(Value.class.getField("VALUE"), 200);
System.out.println(useField());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment