0

I was trying to use this: Change private static final field using Java reflection in order to set static+final field:

import java.lang.reflect.Field; import java.lang.reflect.Modifier; public class Test { public static final String TEST = "hello"; static void setFinalStatic(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); } public static void main(String args[]) throws Exception { setFinalStatic(Test.class.getField("TEST"), "world"); System.out.println(Test.class.getField("TEST").get(null)); System.out.println(Test.TEST); } } 

The code above shows: world hello

How is this even possible?

Edit: This Change private static final field using Java reflection explains why it behaves that way, but is there a different way to proceed so that System.out.println(Test.TEST); prints "world"?

2

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.