mardi 14 mars 2023

Not able to re-assign value to final member using Reflection API

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.





Aucun commentaire:

Enregistrer un commentaire