0

I am trying to change the final member value using reflection API but it is not working.Below is the sample code.

public class Fun {
    private static final String AA = "something";
    public static void getValue() {
        if(AA != null)
            System.out.println("I m here");
    }

}


public class Test {

    @org.testng.annotations.Test
    public void fun() throws ReflectiveOperationException {
        setFinalStaticField(Fun.class, "AA", null);
        Fun.getValue();
    }

    private static void setFinalStaticField(Class<?> clazz, String fieldName, Object value)
            throws ReflectiveOperationException {

        Field field = clazz.getDeclaredField(fieldName);
        field.setAccessible(true);

        Field modifiers = Field.class.getDeclaredField("modifiers");
        modifiers.setAccessible(true);
        modifiers.setInt(field, field.getModifiers() & ~Modifier.FINAL);

        field.set(null, value);
    }
}

The above code is always printing "I m here" ,however I changed the value of the variable to null. Can anyone please help me on that, why this is not working as expected.

amit kumar
  • 59
  • 1
  • 1
  • 11
  • You cannot reassign `static final` fields, not even with reflection; or at least, this does not work because of an optimization of the compiler, where it inlines the use of such variables. But this also does not make sense - the value is fixed, so for example checking if it is `null` is not very useful. Why do you want to do something like this? – Jesper Mar 14 '23 at 15:25
  • Just because you change the `modifiers` attribute of the field, doesn't make the field non-final. All you've done is disable some internal checks that cause an exception to be thrown. – Rob Spoor Mar 14 '23 at 16:12
  • Would the solution here help? https://stackoverflow.com/questions/3301635/change-private-static-final-field-using-java-reflection – Adam Wise Mar 14 '23 at 17:24

0 Answers0