mardi 8 décembre 2015

NoSuchFieldException when use java reflection to set private field value

I have a School class which has a private boolean field hasStudent :

public class School {
  private boolean hasStudent
  ...
}

I have a instance of School:

School mSchool = new School();

I want to set the hasStudent to true with java reflection. I created a function to do it:

    public setValue(Object obj, String fieldName, Object value) throws Exception {
      Field field = obj.getClass().getDeclaredField(fieldName);
      field.setAccessible(true);
      field.set(obj, value);
  }

      // call the above method to set value
     setValue(mSchool, "hasStudent", true);

But I got error:

java.lang.NoSuchFieldException: hasStudent

Why?





Aucun commentaire:

Enregistrer un commentaire