vendredi 27 mars 2020

Java Reflection: setting a final field isn't working

So, I made a ReflectUtil class with some useful methods that allow me to access the java reflection API in a fast and simple way. Based on this the method forceCall can change the value of a private and final field.

This example works absolutely fine:

ReflectUtil.forceCall(Boolean.class, null, "FALSE", true);
System.out.println(String.format("Everything is %s", false));

The output is: Everything is true (so my method is working).

But this just isn't working (it also doesn't work if i try it without my ReflectUtil class):

public class JustForTestingPurposes {
    private static final String field = "no";

    public static void main(String[] args) throws Exception {
        ReflectUtil.forceCall(JustForTestingPurposes.class, null, "field", "yes");
        System.out.println(String.format("Is this working? %s", field));
    }

}

The output is: Is this working? no

I thought, maybe it's because of the way how java assigns values, so I added a 1 sec sleep before executing the code in the main method, with no success.





Aucun commentaire:

Enregistrer un commentaire