I have 2 class (i've simplified my sample, its not really my classes)
class Father {
private Child child;
public Father() {
child = new Child();
}
}
class Child {
private int age;
}
In order to make unit tests, i need to set the value of age
, ONLY from Father
class, using reflection.
Basically, i have a problem setting the final value in age
, and its generating an exception.
1st, i'm retrieving Father
class, and then from it, taking child
field, which works well. My problem is calling ageField.set(ageField, 15);
since ageField is a field and not the actual age
member.
Field field = Father.class.getDeclaredField("child");
field.setAccessible(true);
Object value = field.get("child");
Child child = (Child) value;
Field ageField = value.getClass().getDeclaredField("age");
ageField.setAccessible(true);
ageField.set(ageField, 15);
Fyi, i've looked at the following links, so this is not a duplicate.
Aucun commentaire:
Enregistrer un commentaire