mardi 7 juin 2016

Setting field of a subclass via reflection

I'm trying to set a value of a field of a subclass object:

public void setValue(Serializable target, String fieldName, float changer) {
...
//next I'm accessing field "deal" of sub-class "Mon" of class "Hum"
//Hum target
//String upper value is "Mon"
//String fieldName value is "deal"
//float changer is some valid number
Field theField = target.getClass().getDeclaredField(upper).get(target).getClass().getDeclaredField(fieldName);
switch (theField.getType().getName()) {
    case "float":
        theField.setFloat(target, changer); //the line with error!
        break;
    case "int":
...
}

The code throws

IllegalArgumentException: Can not set float field hb.Hum$Mon.deal to hb.Hum

OK, but when I changed the troubled line to:

theField.setFloat(target.getClass().getDeclaredField(upper).get(target).getClass(), changer)

it threw a NullPointerException. I'm obviously messing up with field access but I can't figure out what exactly I do wrong. Can anyone, please, point to a mistake?





Aucun commentaire:

Enregistrer un commentaire