lundi 14 août 2017

final causes static behavior somehow

I have a code like this:

public class App {
    private final String some;
    public App(){
        some = "old";
    }
    public static void main(String... args) throws NoSuchFieldException, IllegalAccessException {
        App a = new App();
        a.magic();
        System.out.println(a.some);

    }
    private void magic() throws NoSuchFieldException, IllegalAccessException {
        Field field = this.getClass().getDeclaredField("some");
        field.setAccessible(true);
        Field modifiersField = Field.class.getDeclaredField("modifiers");
        modifiersField.setAccessible(true);
        modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
        field.set(this, "new");
        String someDuplicate = (String) field.get(this);
        System.out.println(someDuplicate);
    }
}

the output from this will be

new 
new

but if i'll change variable initialization to this:

private final String some = "old";

the output will be

new
old

seems like inline initialization causes static-like behavior of final non-static field

I could'n find any dock reference to this behavior, may be there is some logical explanation to this.

By the way this way to init field causes behavior like in constructor init case:

{
    some = "old";
}





Aucun commentaire:

Enregistrer un commentaire