Created
April 12, 2022 13:02
-
-
Save DasBrain/ca16053f8e073c8a883bee66302c2fee to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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