vendredi 20 mai 2016

(Java) Access a subclass field with reflection

I have this code :

class A
{

    private void update()
    {
        Field theField = this.getClass().getDeclaredField("myField");

        theField.setAccessible(true);
        theField.set(this, "New Value");
    }

}

class B extends A
{
    private String myField = "hey";
}

But, it throws a IllegalAccessException :

java.lang.IllegalAccessException: Class A can not access a member of class B with modifiers "private"

I know this code is ugly, but this is for automatically fill a field with an annotation. I don't know how to do that, maybe with Unsafe but I need the memory address of the field.

Thanks you for any help.





Aucun commentaire:

Enregistrer un commentaire