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"?

Community
  • 1
  • 1
benji
  • 2,331
  • 6
  • 33
  • 62

0 Answers0