java - Reflection in inhertited classes -


i use method remove html code strings in classes:

public void filterstrings() {      field[] fields = this.getclass().getdeclaredfields();      if (fields == null) {         return;     }      (field f : fields) {          if (f.gettype() == java.lang.string.class) {              try {                  string value = (string) f.get(this);                  f.set(this, methodtoremovehtml(value));              } catch (illegalargumentexception e) {                 e.printstacktrace();             } catch (illegalaccessexception e) {                 e.printstacktrace();             }         }      }  } 

works fine. since caught myself putting method in many classes use, thought i'd let classes inherit baseclass , implement method there. but when this, a: java.lang.illegalaccessexception: access field not allowed on every try.

  1. why happening ,
  2. how can fix this?

i guess fields private, can accessed code inside class contains them, , not superclass.

you have make them accessible calling setaccessible(true); on them or making them public or protected.

    (field f : fields) {          if (f.gettype() == java.lang.string.class) {              try {                 f.setaccessible(true); // make field accessible.                 string value = (string) f.get(this);                 // ... 

Comments