samedi 17 décembre 2016

Filed Value Update With Java Reflection

I took the reference from Change private static final field using Java reflection and wrote below code to update an String type static final field value:

I have one class which contains an Constant like below:

public final class Constants {

    public static final String ACCEPTED = "A";
}

I tried to update it's value using Java Reflection, like below:

Field field = Constants.class.getDeclaredField("ACCEPTED");
    field.setAccessible(true);

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

    String newValue = "B";
    field.set(null, newValue);

After updating value by using above code I tested it like below:

String myUpdatedValue = Constants.ACCEPTED;

Here when I inspected Constants.ACCEPTED the value was being showed was "B", but when I inspected myUpdatedValue, it is showing as "A". Can't understand reason. Even when I pass this value to some other method as parameter, at the method call it's "B" but inside the called method it's "A".





Aucun commentaire:

Enregistrer un commentaire