mardi 26 décembre 2017

Setting private final field via reflection fails when ctor is removed

Suppose I have the following class:

public class SomeClass {

    private final int num;

    public SomeClass(int num) {
        this.num = num;
    }

    public int getNum() {
        return num;
    }

}

When I execute this code to set the num field, everything is fine:

SomeClass obj = new SomeClass(0);

final Field field = SomeClass.class.getDeclaredField("num");
field.setAccessible(true);
Field modField = Field.class.getDeclaredField("modifiers");
modField.setAccessible(true);
modField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(obj, 1);

System.out.println(obj.getNum()); // Prints 1 instead of the initial value 0.

However, when I remove the constructor from SomeClass, this doesn't work anymore and the println statement prints 0.

Can anyone explain this behavior?





Aucun commentaire:

Enregistrer un commentaire