简体   繁体   中英

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 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.

This is how constants work in java.

When a java program is compiled, all references to a compile-time-constant (using a literal or maybe <Classname>.class or similar)are replaced with the constant itself.

You should be able to bypass this by assigning it to the return value of a method or using the new operator(the following example contains both):

private static final String field = getNo();
private String getNo(){
    return new String("no");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM