Created
December 8, 2020 10:53
-
-
Save DasBrain/25c6738610c517ee375aacc86ffebd0c to your computer and use it in GitHub Desktop.
Demostrates that changing static final fields may not work.
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
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